Notes from a Carbon Based Life Form
thoughts, opinions, and drivel. 100% free, guaranteed.

20060224 Friday February 24, 2006

STDOUT, STDERR, and logging shell script output

A shell script was running just fine interactively, but when I tried to automate it, it wasn't behaving as expected, and I hadn't set it up to log it's output to a file.

#!/bin/sh
 
DATE=`date`
echo "Begin: `basename $0` :: $DATE"
echo
echo " Testing for /tmp/foo"
if [ -f /tmp/foo ]; then
echo " /tmp/foo exists, we're good to go"
else
echo " /tmp/foo doesn't exist, not so good to go"
fi
echo " Testing for /tmp/bar"
if [ -f /tmp/bar ]; then
echo " /tmp/bar exists, we're still good to go"
else
echo " /tmp/bar doesn't exist, Doh! Double not so good to go"
fi

Now, that's well, and good, but when it's running, automated, on boot, the output wasn't being captured so I couldn't see what the problem was, or what errors occured. So I started looking for an easy lazy way to log the output of my shell script, which was being run non-interactively. I certainly didn't want to go through the script line by line, and add a " >> $logfile" to the end of every echo, and every command.

Here's what I came up with:

#!/bin/sh
 
LOGFILE="/var/adm/`basename $0`.log"
exec 1>>$LOGFILE
exec 2>&1
 
DATE=`date`
echo "Begin: `basename $0` :: $DATE"
echo
echo " Testing for /tmp/foo"
if [ -f /tmp/foo ]; then
echo " /tmp/foo exists, we're good to go"
else
echo " /tmp/foo doesn't exist, not so good to go"
fi
echo " Testing for /tmp/bar"
if [ -f /tmp/bar ]; then
echo " /tmp/bar exists, we're still good to go"
else
echo " /tmp/bar doesn't exist, Doh! Double not so good to go"
fi

And surprise, surprise. That worked perfectly. :)
Turns out my problem was a typo. I had a 't' where I should have had an 'r'.
Here's what my log looked like:


% cat /var/adm/foo.sh.log
Begin: foo.sh :: Fri Feb 24 01:48:59 EST 2006
 
Testing for /tmp/foo
/tmp/foo exists, we're good to go
Testing for /tmp/bar
/tmp/bar doesn't exist, Doh! Double not so good to go

Posted by tkblog ( Feb 24 2006, 12:13:16 AM EST ) Permalink

Comments:

Post a Comment:

Comments are closed for this entry.

Archives
Language
Links
Referrers