Saturday, July 06, 2013

bash stdout and stderr to file and console

Given a typical bash script which would print to stderr and stdout like:
$ cat testRedirection.sh 
#!/bin/bash -e
# writes to stderr and stdout then dies with exit 1 
echo "out"
echo "err" >&2
exit 1
Suppose you want to send "out" and "err" to a file and also to the console. You might think on doing something like:
#Not good as stderr and stdout are completely redirected (you will see no output on screen)
$ ./testRedirection.sh &> results.log
But actually the below will be your only option as far as I can tell:
$ ./testRedirection.sh > >(tee -a results.log) 2> >(tee -a results.log >&2)
Basically you send stdout and stderr to a couple of streams that use the 'tee' command to guarantee the content is sent to the console still. Note the last ">&2" which is necessary to avoid tee printing the stderr message to stdout.

No comments:

Followers