set -e Misses a Failure Inside a Pipeline Unless pipefail Is Set
set -e makes a Bash script stop when a command fails, but a pipeline's exit status is the status of its last command. When an earlier stage fails and the last one succeeds, the pipeline succeeds and the script carries on with missing or empty data. set -o pipefail makes the pipeline fail when any stage fails, which is why bootstrap scripts start with set -euo pipefail.
What Each Option Catches
| Option | Stops the script when |
|---|---|
-e (errexit) |
a simple command or a pipeline returns non-zero |
-u (nounset) |
the script reads a variable that was never set, such as a mistyped name |
-o pipefail |
any stage of a pipeline fails, not only the last one |
A download written through tee shows the gap:
set -e
curl -fsS "$KEY_URL" | tee /etc/apt/keyrings/repo.asc # curl fails, tee succeeds
apt-get update # runs anyway, with an empty key file
With pipefail, the pipeline returns curl's error and the script stops on that line.
Where set -e Stays Silent Anyway
Bash deliberately ignores failures in some positions, with or without pipefail:
- commands tested by
if,whileoruntil, and any function called from such a test; - commands on the left of
&&or||, and commands negated with!; local var=$(cmd)andexport var=$(cmd): the status checked is that oflocalorexport, not ofcmd. Declare first, then assign (local var; var=$(cmd)).
Marking the Failures You Expect
Some commands may fail legitimately: deleting something already gone, adding an address already present. cmd || true lets the script continue, but it also hides every other failure of that command. An option that expresses the expected case is safer (see Idempotent Scripts Check the Current State Before Changing It).
References
- Linux Administration MOC - hub for shell and Linux notes.
- Idempotent Scripts Check the Current State Before Changing It - expected failures and safe re-runs in the same scripts.
- GNU Bash manual: The Set Builtin -
-e,-uandpipefail, and where-eis ignored. - GNU Bash manual: Pipelines - a pipeline's exit status.
- BashFAQ 105: Why doesn't set -e do what I expected? - the corner cases of errexit.
- ShellCheck - static analysis for shell scripts.