I prefer to write solid shell code, so the errexit & nounset is alway set.
The following code will stop at bad_command line
#!/bin/bash
set -o errexit ; set -o nounset
bad_command # stop here
good_command
I want to capture it, here is my method
#!/bin/bash
set -o errexit ; set -o nounset
rc=1
bad_command && rc=0 # stop here
[ $rc -ne 0 ] && do_err_handle
good_command
Is there any better or cleaner method
My Answer:
#!/bin/bash
set -o errexit ; set -o nounset
if ! bad_command ; then
# error handle here
fi
good_command
I cobbled together a (hopefully) textbook example from all the answers:
Keep with errexit. It can help find bugs that otherwise might have unpredictable (and hard to detect) results.
The above will work fine.
errexit
only requires that the line pass, as you do with thebad_command && rc=0
. Therefore, the above with the 'or' will only run do_err_handle ifbad_command
fails and, as long as do_err_handle doesn't also 'fail', then the script will continue.In bash you can use the trap builtin which is quite nice. See https://unix.stackexchange.com/questions/79648/how-to-trigger-error-using-trap-command
Not sure how portable it is with other shells.. so YMMV
Agree with comments, so if you can give up
errexit
then you can easily shorten your code toI hope this helps.
what if you want to know exit status of bad_command?
I think the simplest way is to disable errexit: