I'm trying my hand at bash script programming and was wondering how to
make my scripts more robust. For example, I have one bash script that
runs daily that makes an incremental backup of my hard-disk and rotates
the daily backups. If this fails, I want the script to send me an email
to let me know something went wrong. This means that every line in the
program that can possibly fail must call a "error" function that sends
an email. Here's an examples of what I have so far:
function error {
echo Failed.
ls -l $SNAPSHOT | mail seanw -s "Backup script failed"
exit
}
if [ -d $BACKUP_NAME.0 ]; then
echo Creating copy of newest backup...
rm -rf $TEMP_BACKUP || error
cp -al $BACKUP_NAME.0 $TEMP_BACKUP || error
echo Updating newest backup copy with rsync...
else
echo No previous backups found. Creating first full backup...
fi
rsync -av --delete-after --delete-excluded \
--exclude=$EXCLUDES $TO_BACKUP $TEMP_BACKUP || error
# snipped the rest...
This works fine, but I need to remember to add the "|| error" snippet
to the end of every command, it looks messy, clutters my code and I
might forget it to do it everywhere. Is there any better way to do
error handling in bash? For example, can I define a function that will
be called when the script fails or use C++ style exceptions? I noticed
that when running Makefiles, make will immediately exit if one of the
commands fail. That's similar to what I'm after, but I need to call a
function on failure.
Would "trap error DEBUG" do what you want?
Or:
set -e
trap error EXIT
--
Chris F.A. Johnson http://cfaj.freeshell.org/shell
===================================================================
My code (if any) in this post is copyright 2005, Chris F.A. Johnson
and may be copied under the terms of the GNU General Public License
You were probably thinking of:
trap error ERR
--
Stéphane