Trap Shell-Script Errors

December 2nd, 2007 by LJ Staff

An easy way to protect shell scripts from creating havoc when they go wrong due to a missing directory is to replace the shell's cd command by a function declared at the start of the script:

cd(){
    if ! builtin cd $1
    then    echo "Failed to cd $1 !!!" >&2
            exit 1
    fi
}

No other changes are needed in the script. An alternative option is to add

set -e

...at the start of a script, then any failing command (outside a construct that tests the return code like if ...) will cause the script to stop. It also encourages you to make sure any other scripts that you call will exit with an appropriate return code: 0 for ok, and anything else for failure.

This Tech Tip was brought to us by Mark in France. Thanks, Mark!

Instant fame is easy at Linux Journal. Just send us your useful Tech Tips to share with the Linux Community, and we'll send you a cool t-shirt for your efforts!

Please note: Tech Tips featured in this specific section of LinuxJournal.com are kindly brought to us by readers and are not necessarily tested by LinuxJournal.com editors.


Special Magazine Offer -- 2 Free Trial Issues!
Receive 2 free trial issues of Linux Journal as well as instant online access to current and past issues. There's NO RISK and NO OBLIGATION to buy. CLICK HERE for offer

Linux Journal: delivering readers the advice and inspiration they need to get the most out of their Linux systems since 1994.

Sorry, offer available in the US only. International orders, click here.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

What does "builtin" in the

On December 26th, 2007 Anonymous (not verified) says:

What does "builtin" in the script do?

Thanks

Another BIG help is 'set

On December 6th, 2007 Anonymous (not verified) says:

Another BIG help is 'set -u', which treats unset variables as an error. I trashed my system once using rsync: i misspelled a variable name, it expanded to nothing, the trailing / caused it to select the root directory as the destination, and the --delete flag promptly deleted everything on my filesystem. :-(

These are the first non-comment lines in all of my shell scripts now:
set -e
set -u

:-)

Disclaimer

On December 6th, 2007 Shawn Powers says:

So your disclaimer is for my file cleanup script, isn't it?

"rm -rf /"

Here's the real tip: Don't listen to Shawn. :)

And now for my disclaimer. If you're new to Linux, I was joking. rm -rf is NOT your friend. It will kick your dog, steal your significant other, and call you ugly. Oh, and delete all your files.

Slight tweak

On December 3rd, 2007 Andrew Kirkpatrick (not verified) says:

If you use "$@" instead of $1, it will work with directory names containing whitespace, as well as handle multiple arguments such as cd -P /path/with/symlink


cd(){
if ! builtin cd "$@"
then echo "Failed to cd $@ !!!" >&2
exit 1
fi
}

Cheers

How is this any better

On November 30th, 2007 Anonymous (not verified) says:

How is this any better than:

if cd some-place
then
ok
else
fail
fi

Multiple uses

On November 30th, 2007 Phil Hughes says:

If you script only has one cd in it, it isn't. But, by defining the function at the start of the script you can protect all cd commands within the script.

In a correctly written

On December 5th, 2007 CoolHand says:

In a correctly written script, one should be checking the existance and permissions of a directory before trying to change to it - and, if necessary, creating the directory if it doesn't.

Where do these kids learn to program

On December 10th, 2007 Anonymous (not verified) says:

Thank you.

Featured Videos

In case you were wondering about the fun side of Linux World Expo, we thought we'd give you a peek at our shenanigans. We at Linux Journal love what we do so much, that we can't help but have a ball wherever we go.

The X Window System is a magnificent platform for many uses, but using it to run an application over a slow network is nearly impossible. This is an introduction to NX, a technology that makes remote applications fly even over commodity internet.

From the Magazine

September 2008, #173

Feeling a bit like a Thermian? Never give up, never surrender! Someday, you could go from underdog to top dog. Just take a look at a few of the underdogs we highlight in this issue: Mutt, djbdns, Nginix, Gentoo, Xara and the program voted mostly likely to fail just a few years back—Firefox. If Firefox not radical enough for you, check out Chef Marcel's column for some more alternatives. Having trouble mapping your program data to your relational database? If so, Rueven Lerner shows you some tricks in his At The Forge column.

Need to run GUI applications on your server in the next state? In his Paranoid Penguin column, Mick Bauer shows you how to do it securely. Kyle Rankin keeps hacking and slashing and shows you a few split screen secrets you may not be familiar with. Finally, we all know what happens next February, but only Doc knows what happens afterward.

Read this issue