I prefer to write solid shell code, so the errexit & nounset is alway set.
The following code will stop at bad_command line
#!/bin/b
Keep with errexit. It can help find bugs that otherwise might have unpredictable (and hard to detect) results.
#!/bin/bash
set -o errexit ; set -o nounset
bad_command || do_err_handle
good_command
The above will work fine. errexit
only requires that the line pass, as you do with the bad_command && rc=0
. Therefore, the above with the 'or' will only run do_err_handle if bad_command
fails and, as long as do_err_handle doesn't also 'fail', then the script will continue.
set -o errexit bad_command || { resp_code=$? echo Bad Thing $resp_code happened }
Just trying to complete the following answer: https://stackoverflow.com/a/32201766/2609399 , which is a very good catch, BTW.
I've faced this limitation a time ago and applied a similar fix for it. Please consider the below code sample.
invokeBashFunction() {
local functionExitCode="0"
/bin/bash -c "
set -o errexit
${*}
" || functionExitCode="${?}"
# add some additional processing logic/code
return "${functionExitCode}"
}
export -f invokeBashFunction
And there are few example of how to use it:
invokeBashFunction bad_function param1 "param 2" param3 && echo "It passed." || echo "It failed!"
if invokeBashFunction bad_function param1 "param 2" param3
then
echo "It passed."
fi
if ! invokeBashFunction bad_function param1 "param 2" param3
then
echo "It failed!"
fi
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
what if you want to know exit status of bad_command?
I think the simplest way is to disable errexit:
#!/bin/sh
set -o errexit
some_code_here
set +o errexit
bad_command
status=$?
set -o errexit
process $status
A clean reliable way to error exit
command_that_error_exits || { echo "Line $LINENO: Failed with Error" 1>&2; exit 1;}