trapping errors in test scripts

Paul Fox pgf at brightstareng.com
Wed May 7 11:35:35 PDT 2008


 > Please consider these 2 examples scripts (tested with bash, dash and zsh):
 > 
 > ,---- [ x1 ]
 > | #/bin/sh
 > |
 > | set -e
 > |
 > | status=0
 > | do-this
 > | test $? -eq 0 || status=1
 > |
 > | if [ $status -eq 0 ]; then
 > | 	echo "### show success" >&2
 > | else
 > | 	echo "*** show some error message" >&2
 > | fi
 > |
 > | exit 0
 > `----
 > 
 > The result from running the above:
 > 
 > ,----
 > | # /tmp/x
 > | /tmp/x: line 6: do-this: command not found
 > `----
 > 
 > And this:
 > 
 > ,---- [ x2 ]
 > | #/bin/sh
 > |
 > | set -e
 > |
 > | status=0
 > | do-this || status=1
 > |
 > | if [ $status -eq 0 ]; then
 > | 	echo "### show success" >&2
 > | else
 > | 	echo "*** show some error message" >&2
 > | fi
 > |
 > | exit 0
 > `----
 > 
 > The result from running the above:
 > 
 > ,----
 > | # /tmp/y
 > | /tmp/y: line 6: do-this: command not found
 > | *** show some error message
 > `----
 > 
 > Now, it seems to me that [ x2 ] behaves more like expected, which implies

i don't agree.  a missing command is quite different than getting
a "failed" result from that command.  your error message is likely
to describe the failure of "do-this" -- but "do-this" never even
got a chance to run.

both methods abort the script (which is good), but the x2 method
continues running when do-this doesn't exist.  with the code
you've shown, that's okay, but often it would be bad.  (put
another way, writing "do-this || status=1" subverts the intention
of "set -e".)

if you want to continue in the absence of "do-this", the test
explicitly:

    if type do-this >/dev/null
    then
	do-this
	... etc ...
    else
	echo do-this command is missing. >&2
    fi

all that being said, i don't think it matters very much.  ;-)

paul
p.s. it's tuesday -- the bikeshed should be red.

 > this method of trapping errors:
 > 
 > ,----
 > | status=0
 > | do-this || status=1
 > `----
 > 
 > is more appropriate than this one:
 > 
 > ,----
 > | status=0
 > | do-this
 > | test $? -eq 0 || status=1
 > `----
 > 
 > when:
 > 
 > ,----
 > | set -e
 > `----
 > 
 > is used, but also when it isn't.
 > 
 > This also implies that scripts using the [ x1 ] method will be more error
 > prone.
 > 
 > Thoughts?
 > 
 > 
 > Cheers,
 > 
 > -- 
 > Cristian
 > _______________________________________________
 > busybox mailing list
 > busybox at busybox.net
 > http://busybox.net/cgi-bin/mailman/listinfo/busybox

=---------------------
 paul fox, pgf at brightstareng.com


More information about the busybox mailing list