Bash Error Checking

January 24th, 2009 by webstersprodigy

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 con‐
sidered 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


No computers were harmed in the 0.178 seconds it took to produce this page.