Fail-Fast Scripts with set -e: Benefits and Caveats
By default, Bash keeps running a script after a command fails. The failed command prints its error, its exit code is stored in $?, and the next line runs as if nothing had happened. set -e changes that: when a command fails, the shell stops the script immediately, with the failed command's exit code. This "fail fast" behavior prevents a script from carrying on in a broken state, but its exact rules contain many exceptions, and understanding them is the difference between a safety net and a false sense of security.
#!/usr/bin/env bash
echo "start"
cp nofile x
echo "reached without set -e"
start
cp: cannot stat 'nofile': No such file or directory
reached without set -e
The script continues past the failure and ends with status 0. With set -e added:
#!/usr/bin/env bash
set -e
echo "start"
cp nofile x
echo "not reached"
start
cp: cannot stat 'nofile': No such file or directory
The script stops at the failed cp and its exit code is 1, the status of cp.
Why Fail Fast
Commands in a script usually depend on each other. If one step fails and the script keeps going, later steps work with missing or wrong data:
cd /srv/build
rm -rf ./*
If cd fails (the directory does not exist, or a permission is missing), the rm runs in whatever directory the script started in. With set -e, the failed cd ends the script before rm runs. Lesson 160 returns to this kind of danger.
The benefits:
- A failure stops the script close to its cause, so the last error message on the screen is usually the relevant one.
- The script's exit code reports the failure to cron, CI systems and calling scripts (lesson 116), instead of the status of some later command that happened to succeed.
- Short scripts get basic error handling without an
|| exitafter every line.
Turning It On and Off
set -e # short form
set -o errexit # long form, same effect
set +e # turn it off again
The option applies from the line where it is set. It can be turned off for a section and on again:
set -e
set +e
false
echo "set +e turned it off"
set -e
false
echo "not reached"
set +e turned it off
The special parameter $- lists the shell's single-letter options. When set -e is active, it contains e:
set -e
echo "$-"
ehB
The Shebang Form
Some scripts put the option in the first line, #!/bin/bash -e. It works when the script is run as a program, but the line is only a comment when the script is passed to bash explicitly:
printf '#!/bin/bash -e\nfalse\necho "reached when run with bash file"\n' > e30.sh
chmod +x e30.sh
./e30.sh; echo "direct: $?"
bash e30.sh; echo "via bash: $?"
direct: 1
reached when run with bash file
via bash: 0
A set -e line inside the script applies however the script is started (lesson 28), so it is the more reliable place.
When set -e Does Not Stop the Script
The Bash manual lists the situations in which a failure is ignored even with set -e. They exist because in these places a non-zero status is part of normal logic, not an error. Each one is shown below with the result from a test run.
Conditions of if, while and until
A command tested by if, elif, while or until is expected to fail sometimes; that is the point of the test:
set -e
if cp nofile x 2> /dev/null; then
echo "copied"
else
echo "if condition failure ok"
fi
echo "continues"
if condition failure ok
continues
Commands in && and || Lists, Except the Last
In a && b and a || b, the commands before the last operator may fail without ending the script:
set -e
cp nofile x 2> /dev/null || echo "|| handled"
false && echo "no"
echo "continues"
|| handled
continues
false && echo no fails as a whole, but false is not the last command of the list, so the script continues. The last command of a list is checked:
set -e
true && false
echo "not reached"
The script ends with status 1 at false.
This rule produces one of the best-known surprises. The line [ -f nofile ] && echo exists fails when the file is missing, but because the failing test is not the last command in the list, the script continues. Put the same line at the end of a function, however, and the function returns that failure as its own status:
set -e
check() {
[ -f nofile ] && echo "exists"
}
check
echo "after check"
The script ends at check with status 1, and after check is never printed. The function call itself is a simple command that failed. Writing the test as an if statement, or ending the function with return 0, avoids the problem.
Negation with !
set -e
! true
echo "! true does not exit"
! true does not exit
A command whose status is inverted with ! never triggers set -e, whatever the result.
Pipelines: Only the Last Command
The status of a pipeline is the status of its last command (lesson 61), and set -e looks only at that:
set -e
false | true
echo "pipeline: only last counts"
pipeline: only last counts
true | false would end the script. A failure in the middle of a pipeline, such as grep finding nothing before sort, is ignored unless set -o pipefail is also set (lesson 120).
Functions Called in a Condition
When a function is called where set -e is ignored (in an if condition, or on the left of && or ||), the option is ignored for every command inside the function as well:
set -e
f() {
false
echo "inside f after false"
}
if f; then echo "f ok"; fi
echo "end"
inside f after false
f ok
end
The false inside f did not stop anything, and f returned 0 because its last command, echo, succeeded. Called on its own line, the same function ends the script at its first command:
set -e
f() {
false
echo "inside f after false"
}
f
echo "end"
Nothing is printed, and the status is 1. The same function behaves in two different ways depending on where it is called, which is why a function that must handle errors should check them explicitly rather than rely on set -e.
The same rule covers a group: { false; echo "group continues"; } || echo "group failed" prints group continues, because the group is on the left of ||.
Failures That Are Hidden
Some failures are not seen by set -e because another command's status replaces them.
local, export and declare
Lesson 117 showed that local x=$(cmd) reports the status of local, not of cmd. Under set -e, the failure of cmd is therefore ignored:
set -e
f() {
local x=$(false)
echo "local hides: continues"
}
f
local hides: continues
export V=$(false) behaves the same way. A plain assignment keeps the status, and does stop the script:
set -e
x=$(false)
echo "not reached"
Declare first and assign on a separate line (local x then x=$(cmd)) to keep the protection.
Command Substitution Inside Another Command
When $( ) appears as an argument of another command, only the outer command's status counts:
set -e
echo "value: $(false; echo inside)"
echo "cmdsub in argument: continues"
value: inside
cmdsub in argument: continues
Commands Inside Command Substitution
By default, the commands inside $( ) do not inherit set -e. The false below does not stop the subshell, and the assignment gets the status of the last command, echo:
set -e
x=$(false; echo "inside cmdsub continues")
echo "x=$x"
x=inside cmdsub continues
Bash 4.4 added the inherit_errexit option. With shopt -s inherit_errexit, the subshell stops at false, the assignment fails, and the script ends with status 1. Ordinary subshells in parentheses ( ... ) do inherit set -e without the option.
When set -e Stops a Script That Is Working Correctly
The opposite problem also occurs: set -e ends a script on a non-zero status that was not an error at all.
Commands That Use Status 1 as an Answer
grep returns 1 for "no match", diff returns 1 for "files differ", and grep -c returns 1 when the count is zero (lesson 116). Under set -e, such an answer ends the script:
set -e
count=$(grep -c gamma words.txt)
echo "count=$count"
The script ends at the assignment with status 1, and count=0 is never printed. Adding || true accepts the status:
set -e
count=$(grep -c gamma words.txt || true)
echo "count=$count"
count=0
|| true accepts every failure, including real errors such as a missing file. When the difference matters, save the status and check it (lesson 117):
set -e
rc=0
grep -q gamma words.txt || rc=$?
echo "rc=$rc"
rc=1
Now the script can treat 1 as "not found" and stop on 2.
Arithmetic That Evaluates to Zero
An arithmetic command (( expr )) returns 1 when the expression's value is 0 (lesson 73). (( i++ )) with i equal to 0 evaluates to the old value, 0, so it fails:
set -e
i=0
(( i++ ))
echo "not reached"
The script ends with status 1. (( ++i )) evaluates to the new value, 1, and i=$((i + 1)) is an assignment that always succeeds:
set -e
i=0
(( ++i ))
echo "++i ok i=$i"
++i ok i=1
Finding Out Where the Script Stopped
set -e ends the script silently: the only message is whatever the failed command printed, and some commands print nothing (grep -q, false, [ ]). An ERR trap (lesson 123) runs whenever a command fails in a place where set -e would act, which makes it a good place to report the location:
#!/usr/bin/env bash
set -e
trap 'echo "error on line $LINENO, status $?" >&2' ERR
cp nofile x 2> /dev/null
echo "not reached"
error on line 5, status 1
$LINENO holds the line number of the failing command, and $? its status. Lesson 126 covers tracing with bash -x, which shows every command as it runs.
Using set -e Sensibly
set -e is a safety net, not a full error handling strategy. Many experienced Bash authors use it; others avoid it because of the exceptions above. Both positions follow from the same facts:
- It catches unexpected failures in straightforward sequences of commands, which is where most scripts spend most of their lines.
- It does not catch failures in conditions, in
&&and||lists, in functions called from conditions, in the middle of pipelines, or behindlocalandexport. - It stops scripts on status values that are answers rather than errors, unless those commands are written as conditions or followed by
|| true.
If you use it, combine it with explicit checks for the steps that matter most:
#!/usr/bin/env bash
set -e
src=$1
dest=$2
# a step whose failure needs a clear message: checked explicitly
if ! cd -- "$dest"; then
echo "cannot enter $dest" >&2
exit 1
fi
# a command whose "no match" status is a normal answer
if grep -q TODO -- "$src"; then
echo "note: $src contains TODO items"
fi
# the remaining steps rely on set -e to stop on failure
cp -- "$src" .
gzip -f -- "${src##*/}"
echo "archived ${src##*/}.gz in $dest"
The cd and the grep are written as conditions, so their failures are handled where they occur. The copy and compression steps are plain commands; if either fails, set -e stops the script with the failing command's status. In a test with a source file that did not exist, grep printed its error and returned 2, the if treated that like "no TODO items", and the following cp failed and stopped the script with status 1.
Lesson 120 adds set -u and set -o pipefail, which close two of the gaps described here, and lesson 121 combines all three options.
The examples were run with Bash 5.2.21 and GNU coreutils 9.4. Error messages are shown as printed by the commands; Bash itself prints nothing when set -e ends a script.