Trap Shell-Script Errors

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:

    if ! builtin cd $1
    then    echo "Failed to cd $1 !!!" >&2
            exit 1

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

set -e 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 are kindly brought to us by readers and are not necessarily tested by editors.