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?
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?
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
.
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