BASH Script Error Handling
You can catch errors returned by your commands in BASH shell scripts with "$?". In this example we will do a backup rsync of our home directories to our file server. If a program gives anything but a zero return code, there has been an error of some type. With this method, any non-zero return codes will be reported, along with the output from the previous command.
#!/bin/bash
SRCDIR="/home"
BACKUPDIR="fileserver:/home_backup"
CMD=`rsync -aq --partial --delete "$SRCDIR" "$BACKUPDIR"`
if [ $? != 0 ]; then
{
echo "BACKUP ERROR: problem syncing $SRCDIR to $BACKUPDIR"
echo $CMD
exit 1
} fi
This script will run silently, unless there is an error. We could then call this script daily from cron, mailing any error output to root:
# crontab -e
# daily home backup
0 4 * * * /root/bin/backup.sh</div>