Monday, October 22, 2007

Redirect stderr to both screen and file at the same time

I recently ran into a situation where I need to run a command and have the error output recorded in a file while displaying it on the screen at the same time. It turns out the 'tee' command comes in handy in this case.
$ command 2>&1 | tee err.out

To redirect stdout and stderr to different files, and have the stderr goes to the screen as well:
$ command 2>&1 > std.out | tee err.out

To redirect stdout and stderr to the same file while having the stderr displayed on the screen, too:
$ command 2>&1 > all.out | tee -a all.out

The last trick is particularly handy when it comes to writing a cron job. The crontab will only send out email when there is stderr outputs while writing the output to the same file as the stdout.

No comments:

Post a Comment