Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Error handling in bash scripts

2 views
Skip to first unread message

Wilson

unread,
Feb 1, 2005, 7:35:35 PM2/1/05
to
Hi,

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.

Chris F.A. Johnson

unread,
Feb 1, 2005, 7:54:08 PM2/1/05
to

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

Wilson

unread,
Feb 1, 2005, 8:11:18 PM2/1/05
to
Thanks very much for your quick response! I gave it a quick test and it
works perfect. This will output "Error!" at the prompt twice:
$ function error { echo Error!; }
$ trap error DEBUG
$ fogkrpogkrewpo
$ rm file_that_does_not_exist

Stephane CHAZELAS

unread,
Feb 2, 2005, 3:52:24 AM2/2/05
to
2005-02-2, 00:54(+00), Chris F.A. Johnson:
[...]

> Would "trap error DEBUG" do what you want?

You were probably thinking of:

trap error ERR

--
Stéphane

0 new messages