Roland Turner

about | contact

Prefixing stdout and stderr with helpful markers

I’m testing a piece of logging code, so I care a lot about what goes where. I figured that there had to be a shell one-liner to allow me to mark stdout/stderr without any setup or code changes. Here it is:

(( some_command | sed '-es/^/stdout: /' >&3 ) 2>&1 | sed '-es/^/stderr: /') 3>&1

So, for a trivial example:

$ ((( echo out ; echo err >&2; ) | sed '-es/^/stdout: /' >&3 ) 2>&1 | sed '-es/^/stderr: /') 3>&1
stderr: err
stdout: out
$

As the example shows, sequence between stdout and stderr may not be preserved.