Strict mode - set -e, -u and pipefail
What set -e, set -u and set -o pipefail each change, the cases where -e silently does nothing, and why strict mode is a safety net, not a guarantee.
Exit status and && / || listsConditionals with if, test and double bracketsFunctions, arguments and scopeArrays and associative arrays
Strict mode - set -e, -u and pipefail
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- By default Bash keeps running after a failed command. `set -e` makes the script exit when a simple command fails, `set -u` makes using an unset variable an error, and `set -o pipefail` makes a pipeline fail if any stage fails.
- `set -e` is switched off in conditions: inside `if`, on the left of `&&` or `||`, after `!`, and in any function called from such a place. It is not a complete safety net.
- `((count++))` returns status 1 when `count` is 0, so under `set -e` it kills the script. Append `|| true` or use `count=$((count + 1))`.
- `set -u` catches typos like `$dirr`, and `${var:-}` supplies an explicit default when emptiness is expected. In Bash older than 4.4, including macOS 3.2, an empty array expanded as `"${a[@]}"` counts as unbound.
- Strict mode finds problems early but does not replace explicit checks, and error messages from a bare `set -e` exit tell you little about why.
Bash’s default is to keep going
Most languages stop when something goes wrong. A shell script doesn’t. If a command fails, Bash reports it and moves to the next line, which is the right behaviour at an interactive prompt and a dangerous one in a script. Here is what that looks like:
#!/usr/bin/env bash
cd /nonexistent
echo "still ran, in $PWD"
rm -f scratch.tmp
dir=$undefined_name
echo "dir is [$dir]"
$ ./loose.sh
./loose.sh: line 2: cd: /nonexistent: No such file or directory
still ran, in /work/l36
dir is []
The cd failed, and everything after it ran in the wrong directory. The unset variable became an empty string without a word. If the next line had been rm -rf "$dir"/, you can see where this goes. ShellCheck warns about both lines: SC2164 for the unchecked cd, SC2154 for the undefined variable.
Three settings make a script stricter. People call the combination “unofficial strict mode”.
set -e: stop on failure
With set -e, the shell exits as soon as a simple command returns non-zero:
$ ./strict.sh; echo "status: $?"
./strict.sh: line 3: cd: /nonexistent: No such file or directory
status: 1
That script began with set -euo pipefail, and echo "never reached" never ran. The script’s own status is the failing command’s.
set -u: unset variables are errors
$ ./unset.sh; echo "status: $?"
start
./unset.sh: line 4: undefined_name: unbound variable
status: 1
This catches typos, such as $dirr for $dir, that would otherwise become an empty string. When emptiness is expected, say so with a default: ${name:-}.
set -o pipefail: a pipeline fails if any part fails
Without it, a pipeline’s status is its last command’s, which hides earlier failures:
$ ./pipe.sh
without pipefail: pipeline status is 0
with pipefail: pipeline status is 2
Both runs used grep -c ... no-such-file.log | tr. Without the option, the missing file went unnoticed (status 0, from tr). With it, the status was 2, from grep. ShellCheck noted that the count variable was unused in my test script, which is true and unimportant.
Where set -e does nothing
This is the part that surprises people. set -e is deliberately off in places where a failure is a normal part of the logic. I ran a script that hits each of them, and it carried on through all six:
$ ./traps.sh; echo "status: $?"
1. || list: no exit
2. && list: no exit
3. if condition: no exit
4. negated: no exit
5. count++ from 0 needs || true (count=1)
inside f after false
f ok
6. function in an if: set -e switched off inside
status: 1
The cases: a command on the left of || or &&, an if condition, a command negated with ! (ShellCheck flags the bare ! false as SC2251), and, subtly, a whole function called from a condition. Line 6 shows it: false failed inside f, yet inside f after false still printed, because f was called in an if. A function that is safe on its own can lose its protection when someone calls it that way.
Look at item 5. The statement ((count++)) has status 1 when count was 0, because the arithmetic value of the expression is 0, and the shell treats a zero result as “false”. Under set -e that line kills the script (I ran set -e; count=0; ((count++)); echo reached and reached never printed, status 1), unless it’s followed by || true. Writing count=$((count + 1)) avoids the problem. The final line of the script, x=$(false), did trigger the exit (status 1), since a failing command substitution in a plain assignment counts.
The empty-array trap on older Bash
set -u has a version-specific wrinkle. This script expands an empty array:
$ ./arr.sh; echo "status: $?"
empty array has 0 items
[]
finished
status: 0
$ /bin/bash ./arr.sh; echo "3.2 status: $?"
empty array has 0 items
./arr.sh: line 5: empty[@]: unbound variable
3.2 status: 1
Bash 5.3 accepts "${empty[@]}" under set -u. macOS’s 3.2 treats it as an unbound variable and aborts. The fix that works on both is ${empty[@]+"${empty[@]}"}, which I didn’t run here. As far as I know Bash 4.4 fixed this, but I only had 3.2 and 5.3 to test, so I can’t confirm the version boundary.
Safety net, not a guarantee
Keep these limits in mind. Strict mode helps most as a first line of defence in short scripts. It gives you an abrupt exit with a thin message (“line 3: cd: …”), which is why the traps lesson pairs it with cleanup and context. It also doesn’t replace explicit checks for the cases you care about, since the exemptions above mean it can silently stand down. Plenty of experienced scripters dislike relying on set -e for that reason, and the longer You Suck at Programming video linked below argues exactly that. I haven’t heard its argument, only seen its title.
The standard opening is set -euo pipefail right after the shebang. I’d treat each flag separately: -u and pipefail are cheap and catch real mistakes, while -e is the one with surprises.
About the video
anthonywritescode’s “bash ‘strict mode’: -euo pipefail” is episode 201, 10 minutes 29 seconds, published in January 2021. The description says it goes over an unofficial strict mode and what each flag does, and I had no transcript. It is in English. The second view is Anthony’s own follow-up, “bash strict mode gotcha”, and the third is the sceptical You Suck at Programming video I mentioned. I judged both by title.
Where this fits
Strict mode makes a script exit abruptly. The next lesson makes that exit tidy: traps and cleanup.
Check yourself
A script runs `cd /nonexistent` and then `rm -rf build`. What does `set -e` change?
The failing `cd` ends the script before `rm` runs. Without it, `rm -rf build` runs in whatever directory the script was already in.
Why does `if some_function; then` not stop when a command inside `some_function` fails under `set -e`?
In a condition context, `set -e` is ignored for the whole function. The failure only becomes the function's return status, and the code after it keeps running.
What does `set -o pipefail` change for `grep pattern missing.log | wc -l`?
Without it the pipeline's status is `wc`'s, 0. With it, the status is the rightmost non-zero status, here grep's 2 for a missing file, so the failure isn't hidden.
Why is `set -u` useful, and what does `${var:-}` do?
`set -u` turns a mistyped or missing variable into an immediate error instead of an empty string. `${var:-}` supplies an empty default on purpose when an unset variable is acceptable.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.