Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect stdout and stderr to a single file with prefixes

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?

like image 403
João Portela Avatar asked Mar 12 '10 12:03

João Portela


2 Answers

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
like image 154
ephemient Avatar answered Nov 08 '22 12:11

ephemient


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.

like image 35
mouviciel Avatar answered Nov 08 '22 12:11

mouviciel