I wanted to find a way of running a script in cron and output the exit code, and error message, to syslog if it failed. Here’s what I came up with…

output=`/usr/bin/scripts/test.sh 2>&1`; code=$?; if ["$code" -ne 0]; then err_msg=`echo "$output" | tail -1`; logger -t "CRONERROR" "Exit Code = $code: $err_msg"; fi; echo "$output" > /usr/bin/scripts/log/test.log;

It’s not pretty but it works and makes it easy for me to pick this up with Nagios. Please note you’re probably going to want to use set -e and set -o pipefail in your scripts for this to function correctly. See this great post about Writing Robust Shell Scripts.

UPDATE:  I’ve updated this to cope with bash scripts that produce a lot of output. Just the exit code and, hopefully error message, will be logged in /var/log/messages (the error message should be the last line of output). The rest of the script output will be written to a file in /usr/bin/scripts/log/test.log