Thursday, May 28, 2009

Logging Standard Error (stderr) without redirecting every command

Hi all,

Recently I had an overnight process fail without telling anybody why. After ascertaining where the fault occurred I re-ran that particular segment of code only to find I'd left a character out of a variable - a simple error that brought this old bourne shell script to its knees. If the error message (which was spouted to stderr and thus to an unmonitored mailbox) had been logged, we wouldn't have needed to do the autopsy.

Fortunately, the bourne shell, although ancient, allows one to create file handles just like Bash does, and both allow you to override standard error and standard input:


exec 2>stderr.txt
exec 1>stdout.txt

echo This will go to standard error. >&2
echo This will go to standard output.

exit 0

In Bash, you can redirect both standard output and standard error to the same file. The Bourne shell doesn't allow this, however you can do this by redirecting standard error to standard output by replacing stderr.txt with &1 - whatever appears in standard error goes to standard output, which goes to stdout.txt (in our above example).

Hopefully this makes some scripting tasks easier for somebody. I thought it was just the bee's knees myself.

No comments:

Post a Comment