views:

132

answers:

2

I am writing a bash script and need to redirect the stdout and stderr output of a command i run to a single file, prefixing each line with stderr or stdout, accordingly.

is there a simple way to do this?

+4  A: 

Try this:

(myCommand | sed s/^/stdout:/ >> myLogfile) 2>&1 | sed s/^/stderr:/ >> myLogFile

The first pipe inserts a stdout: prefix to the standard output of myCommand and appends it to myLogFile.

The parenthesis are used to make a single command of all of that. They tell that further redirections apply to what is inside parenthesis and not to sed only.

Then standard error is redirected to standard output with 2>&1 (remember that original standard output has already been redirected to a myLogFile). Second pipe inserts a stderr: prefix to it and appends it to myLogFile.

mouviciel
I was groping my way towards this, but yours is much cleaner.
Andrew B
can you elaborate on that answer? i think i understand it, except for the parentheses...
João Portela
ephemient
unfortunately this approach does not preserve order... :(
João Portela
+3  A: 

annotate-output, from Debian's devscripts, does this.

The example in its man page:

$ annotate-output make
21:41:21 I: Started make
21:41:21 O: gcc -Wall program.c
21:43:18 E: program.c: Couldn't compile, and took me ages to find out
21:43:19 E: collect2: ld returned 1 exit status
21:43:19 E: make: *** [all] Error 1
21:43:19 I: Finished with exitcode 2
ephemient
chose this answer because it is better at preserving order, although you have to be flushing the output all the time...
João Portela