Bash Error Checking

I was reading an oriley bash scripting book, and they had an entire chapter dedicated to error checking in bash.  For me, this was a little weird since I think the way they handled it made the code cluttered.

They have cascaded statements like

if [ $ -ne 0 ]; then
#handle error
elif…

For me, this is strange.  I think in a bourne shell, the best way is to just set the -e flag, which according to the man page

-e errexit If not interactive, exit immediately if any untested command fails. The exit status of a command is considered to be explicitly tested if the command is used to control an if, elif, while, or until; or if the command is the left hand operand of an “&&” or “||” operator.

This can be accomblished by

set -e

in your script.

Error handling is a balancing act between doing too much and handling everything (thus making the code unreadable) and not checking enough.  Normally, if I need much more error checking than that, time to pull out the python.

One Response to Bash Error Checking

  1. mopey says:

    Actually, other cool flags

    sh -n script checks for syntax errors without executing
    sh -v script echos commands before running
    sh -x script echos commands after processing on the command line
    sh -u script gives an error message when undefined variables are used.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 32 other followers