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
Continue to write solid shell code.
You do it right if bad_command is really a command. But be careful with function calls in if, while, ||, && or !, because errexit will not work there. It may be dangerous.
If your bad_command is actually bad_function you should write this:
set -eu
get_exit_code() {
set +e
( set -e;
"$@"
)
exit_code=$?
set -e
}
...
get_exit_code bad_function
if [ "$exit_code" != 0 ]; then
do_err_handle
fi
This works well in bash 4.0. In bash 4.2 you only get exit codes 0 or 1.