November 26, 2026

Bash Strict Mode: What set -euo pipefail Does and Where It Bites

Terminal on a monitor at night showing a short shell script stopped at a highlighted error line

A five-line script with set -euo pipefail at the top, a counter starting at zero and ((count++)) inside a loop ran on a test container and printed nothing. No error message, no line number, no “processed a.” The shell just stopped and reported exit status 1. The counter was the only thing that went wrong, and it did not go wrong at all: incrementing zero is a perfectly good operation that happens to return a status the strict-mode flags treat as failure. The three flags catch real disasters, and they also stop scripts for reasons nobody would guess from reading them.

Video: You Suck at Programming on YouTube

The script that keeps going after cd fails

Bash’s default is to shrug and run the next line

Without any flags, a failed command in a Bash script is a printed complaint followed by business as usual. On the Ubuntu 24.04 test container (GNU Bash 5.2.21), this script:

#!/usr/bin/env bash
cd /nonexistent-dir
echo "deleting old build files in $PWD"

produced:

1.sh: line 2: cd: /nonexistent-dir: No such file or directory
deleting old build files in /tmp/bs
[exit status: 0]

The cd failed, the script carried on in whatever directory it started in, and the whole run reported success. Swap that echo for an rm -rf ./* and the boiler room floods. Adding set -e changes the ending:

1e.sh: line 3: cd: /nonexistent-dir: No such file or directory
[exit status: 1]

The Bash Reference Manual’s entry for the set builtin defines -e as “Exit immediately if a pipeline … which may consist of a single simple command,” fails, and then lists a long run of exceptions, which is where the trouble lives.

Basement pipe manifold with one valve padlocked shut, a metaphor for a script stopping on error

What -u and pipefail add

One catches typos in variable names, the other catches failures hiding mid-pipe

-u (nounset) turns an unset variable into an error. The manual says unset variables and parameters are treated as errors during expansion, apart from the special parameters @ and * and arrays subscripted with them, and that a non-interactive shell exits. The test:

#!/usr/bin/env bash
set -eu
echo "target: ${DEPLOY_DIR}/releases"
echo "never printed"
2.sh: line 3: DEPLOY_DIR: unbound variable
[exit status: 1]

Without -u, that line would have expanded to /releases, a path at the root of the filesystem. A misspelled or forgotten variable is one quiet way for a script to aim at the wrong directory, and -u makes it loud.

Pipelines need the third flag. By default a pipeline’s status is the status of its last command, so a failure on the left side is invisible. With only set -e:

grep needle /nonexistent-file | sort
echo "pipeline status was $?, script kept going"
grep: /nonexistent-file: No such file or directory
pipeline status was 0, script kept going
[exit status: 0]

sort succeeded at sorting nothing, so the pipeline succeeded. The manual describes -o pipefail as making the pipeline’s return value “the value of the last (rightmost) command to exit with a non-zero status,” or zero if all succeed. With set -eo pipefail, the same script stops with grep’s own status:

grep: /nonexistent-file: No such file or directory
[exit status: 2]

The phrase “unofficial bash strict mode” comes from Aaron Maxwell’s article, which recommends set -euo pipefail followed by IFS=$'\n\t'. He explains the IFS line as meaning “word splitting will happen only on newlines and tab characters,” so filenames with spaces stop breaking loops. That fourth line is a separate decision and changes how every unquoted expansion in the script behaves.

Where people get burned

Ten tested snippets, and the ones that fail without a word

Every snippet below starts with set -euo pipefail and ran under Bash 5.2.21 on the test container.

1. Arithmetic that evaluates to zero. The opening example:

count=0
for f in a b c; do
  ((count++))
  echo "processed $f, count=$count"
done
[exit status: 1]

((count++)) is a post-increment, so the expression’s value is the old value, 0, and the manual’s entry for (( )) says that when the expression’s value is zero, “the return status is 1.” Nothing is printed because no command printed an error; -e simply saw a non-zero status. count=$((count + 1)) is an assignment, which returns 0, and the same loop then runs to the end.

2. grep that finds nothing.

printf 'alpha\nbeta\n' > list.txt
matches=$(grep gamma list.txt)
echo "matches: $matches"
[exit status: 1]

A grep with no matches exits 1, and in an assignment that status becomes the assignment’s status. Silent again. Maxwell’s article covers this case and suggests || true, as in matches=$(grep gamma list.txt || true). For a yes-or-no question, if grep -q gamma list.txt; then is clearer, because a test in an if is one of the places where -e does not apply.

3. A pipeline that works on small input and dies on big input.

seq 1 100000 | head -n 1
echo "never printed"
1
[exit status: 141]

head exits after one line, seq gets a broken pipe when it writes the next chunk, and dies on SIGPIPE. The Bash manual’s exit status page says a command killed by signal N gets “128+N as the exit status.” On the container, kill -l 13 prints PIPE, and 128 + 13 = 141. With pipefail, that 141 becomes the pipeline’s status, and -e exits. Five runs gave 141 five times. The cruel part was the control run: with seq 1 3 instead of 100,000, PIPESTATUS came back 0 0, because seq finished writing before head closed the pipe. The script passes every test on small data and fails on the production log.

4. A function called from an if.

check() {
  false
  echo "check: still running after false"
}
if check; then echo "check passed"; fi
check: still running after false
check passed

The false inside the function was ignored completely, and the function returned 0 from its last echo. The manual explains why: when a function runs in a context where -e is ignored, such as an if test or the left side of ||, the setting has no effect on the commands inside it. Calling the same function bare, on its own line, exits at the false, so the same body behaves two ways depending on who calls it.

5. local hides a failure.

local_fail() {
  local out=$(false)
  echo "local hid the failure, out='$out'"
}
local hid the failure, out=''

local is a command with its own exit status, which is 0 when the declaration succeeds, and that status replaces the status of the substitution. Declaring first (local out2) and assigning on the next line (out2=$(false)) let -e catch it.

6. Errors inside a command substitution. set -e is not passed into $( ) by default:

v=$(false; echo "inside substitution, kept going")
echo "v=$v"
v=inside substitution, kept going
[exit status: 0]

The shopt documentation describes inherit_errexit as making command substitution inherit errexit “instead of unsetting it in the subshell environment.” With shopt -s inherit_errexit added, the same script exited with status 1.

7. A conditional at the end of a function.

main() {
  [[ -f /etc/missing.conf ]] && echo "found config"
}
main
echo "after main"
[exit status: 1]

The && line itself is exempt from -e. The manual’s exceptions cover most commands in && and || lists. But it is the last command in the function, so its status, 1, becomes the function’s return value, and the call to main is not exempt. The identical line at the top level of a script, followed by more commands, did not stop anything; the run printed the next line and exited 0.

8. Positional parameters under -u. echo "first arg: $1" with no arguments died with $1: unbound variable. ${1:-none given} supplies a default, and ${LANG_OVERRIDE-} expands an optional variable to an empty string without tripping -u. Both ran clean.

9. Empty arrays, which did not bite. arr=() followed by for x in "${arr[@]}" ran without complaint under -u on Bash 5.2.21, matching the manual’s exception for arrays subscripted with @. Scripts that will run on much older Bash builds deserve a test on those builds before anyone relies on this.

10. The silence itself. Cases 1, 2, 5 and 7 stopped with no message at all. A cron job that dies that way leaves only an exit status, if anything is recording it.

Water from a large tank overflowing a small funnel, illustrating a pipeline where the reader stops early and the writer breaks

Getting a line number when strict mode stops a script

An ERR trap turns a silent exit into a log line

The fix for silent exits is to make the shell say where it stopped. -E (errtrace), per the manual, means an ERR trap “is inherited by shell functions, command substitutions,” and subshells. Combined with a trap:

#!/usr/bin/env bash
set -Eeuo pipefail
trap 'echo "error: line $LINENO: \"$BASH_COMMAND\" exited $?" >&2' ERR
count=0
((count++))
echo "never printed"
error: line 5: "((count++))" exited 1
[exit status: 1]

The counter bug from the opening, which took a silent exit to find, now names itself. For scripts run on a schedule, sending that trap’s output to a log or the journal matters more than any of the three flags; the earlier post on systemd timers vs cron covers where scheduled output ends up. Exit statuses also carry meaning past the script itself. git bisect run, for one, reads a test script’s exit code to decide whether a commit is good or bad, so a script that dies at the wrong line feeds bisect a wrong answer.

The case against set -e

Some of the most experienced Bash people say not to use it at all

The Bash wiki at mywiki.wooledge.org keeps a page, BashFAQ/105, devoted to why set -e does not do what people expect. Its contributor GreyCat’s recommendation is blunt: “don’t use set -e. Add your own error checking instead.” The advice is not new; a 2023 post on smoser’s blog was already quoting it and siding with it.

The argument has weight. What -e provides is a set of rules about which statuses count, and a script written under it can pass review and still exit at a line nobody suspected or keep running through a failure inside a function called from an if. Explicit checks like cd "$dir" || exit 1 say exactly what is guarded and leave nothing to the exceptions list.

The counterweight is the first test in this post. A script with no flags and no explicit checks ran an echo in the wrong directory and reported success. For a script that has neither strict mode nor careful checks, the choice is between “exits too often, sometimes silently” and “never exits, always reports success,” and the first fails closer to safe. It is a padlock that sometimes jams, measured against an open door.

Mechanical tally counter on a workbench beside a printout with one line circled, representing a counter bug found by line number

A strict-mode header that reports where it stopped

Five lines, plus habits for the cases the flags cannot see

A header that matches the tests above:

#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit
trap 'echo "error: line $LINENO: \"$BASH_COMMAND\" exited $?" >&2' ERR

The habits that went with it in testing: assignments instead of ((x++)) for counters; if grep -q for questions and || true where an empty result is fine; local on its own line before the assignment; ${1:-default} and ${VAR-} for optional input; and a large-input test of any pipeline that ends in head, grep -m or anything else that stops reading early. Scripts that back up data, like the ones in the post on backing up a live SQLite database, are the ones where a silent mid-run exit costs the most, since the failure shows up weeks later as a backup that is not there.

None of this makes -e predictable in functions called from conditionals. The manual’s rule about ignored contexts still holds, and no shopt switches it off. Which of the ten cases above has already stopped one of your cron jobs without a word?

Sources

  • GNU Bash Reference Manual, The Set Builtin: https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html
  • GNU Bash Reference Manual, The Shopt Builtin: https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html
  • GNU Bash Reference Manual, Exit Status: https://www.gnu.org/software/bash/manual/html_node/Exit-Status.html
  • GNU Bash Reference Manual, Conditional Constructs: https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html
  • Aaron Maxwell, “Use the Unofficial Bash Strict Mode (Unless You Looove Debugging)”: http://redsymbol.net/articles/unofficial-bash-strict-mode/
  • Greg’s Wiki, BashFAQ/105: https://mywiki.wooledge.org/BashFAQ/105
  • smoser’s thoughts, “set -e” post (April 27, 2023): https://smoser.github.io/2023/04/27/set-e-bad.html
  • x9m8, Systemd timers vs cron: https://x9m8.com/systemd-timers-vs-cron/
  • x9m8, Git bisect: find the breaking commit: https://x9m8.com/git-bisect-find-breaking-commit/
  • x9m8, Back up a live SQLite database safely: https://x9m8.com/sqlite-backup-safely-while-running/

489 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *