One point missed in the existing answers is show how to inherit the error traps. The bash
shell provides one such option for that using set
-E
If set, any trap on ERR
is inherited by shell functions, command substitutions, and commands executed in a subshell environment. The ERR
trap is normally not inherited in such cases.
Adam Rosenfield's answer recommendation to use set -e
is right in certain cases but it has its own potential pitfalls. See GreyCat's BashFAQ - 105 - Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected?
According to the manual, set -e exits
if a simple commandexits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while
or until
keyword, part of the test in a if statement
, part of an &&
or ||
list except the command following the final && or ||
, any command in a pipeline but the last
, or if the command's return value is being inverted via !
".
which means, set -e
does not work under the following simple cases (detailed explanations can be found on the wiki)
Using the arithmetic operator let
or $((..))
( bash
4.1 onwards) to increment a variable value as
#!/usr/bin/env bash
set -e
i=0
let i++ # or ((i++)) on bash 4.1 or later
echo "i is $i"
If the offending command is not part of the last command executed via &&
or ||
. For e.g. the below trap wouldn't fire when its expected to
#!/usr/bin/env bash
set -e
test -d nosuchdir && echo no dir
echo survived
When used incorrectly in an if
statement as, the exit code of the if
statement is the exit code of the last executed command. In the example below the last executed command was echo
which wouldn't fire the trap, even though the test -d
failed
#!/usr/bin/env bash
set -e
f() { if test -d nosuchdir; then echo no dir; fi; }
f
echo survived
When used with command-substitution, they are ignored, unless inherit_errexit
is set with bash
4.4
#!/usr/bin/env bash
set -e
foo=$(expr 1-1; true)
echo survived
when you use commands that look like assignments but aren't, such as export
, declare
, typeset
or local
. Here the function call to f
will not exit as local
has swept the error code that was set previously.
set -e
f() { local var=$(somecommand that fails); }
g() { local var; var=$(somecommand that fails); }
When used in a pipeline, and the offending command is not part of the last command. For e.g. the below command would still go through. One options is to enable pipefail
by returning the exit code of the first failed process:
set -e
somecommand that fails | cat -
echo survived
The ideal recommendation is to not use set -e
and implement an own version of error checking instead. More information on implementing custom error handling on one of my answers to Raise error in a Bash script