Combining Strict Mode Options Safely
"Strict mode" is the informal name for turning on three shell options together at the top of a Bash script:
set -euo pipefail
Lesson 119 covered set -e (stop when a command fails), and lesson 120 covered set -u (treat unset variables as errors) and set -o pipefail (let a failure anywhere in a pipeline count). Each option closes a different gap, and together they turn many silent mistakes into immediate, visible failures. They also interact with each other and with the rest of the script in ways that are easy to get wrong. This lesson shows how to combine them, which extra settings complete the picture, and which coding patterns keep a strict script working as intended.
What Each Option Contributes
| Option | Long form | Catches |
|---|---|---|
-e | set -o errexit | A command fails and the script carries on as if nothing happened |
-u | set -o nounset | A misspelled or never-assigned variable expands to an empty string |
-o pipefail | set -o pipefail | A command early in a pipeline fails but the last command succeeds |
No single option covers the others. set -e alone does not notice a failed grep in grep ERROR file | sort, because the pipeline's status is that of sort. pipefail alone changes the pipeline's status but does not stop the script. set -u is about variables, not command statuses at all. That is why they are normally used as a set.
Spelling the Line
These lines all have the same effect:
set -euo pipefail
set -e -u -o pipefail
set -o errexit -o nounset -o pipefail
Running each one and printing the enabled single-letter flags in $- and the long names in $SHELLOPTS gave the same result every time:
ehuBc
braceexpand:errexit:hashall:interactive-comments:nounset:pipefail
In set -euo pipefail, the letters e and u are separate flags, and o takes the next word, pipefail, as its argument. The long form is easier to read for someone who has not memorized the letters; the short form is what most scripts use.
Put It on Its Own Line, Not in the Shebang
It is tempting to move the options into the shebang line (lesson 26). On Linux this does not work, because the kernel passes everything after the interpreter path as a single argument:
#!/usr/bin/env bash -euo pipefail
echo hi
/usr/bin/env: 'bash -euo pipefail': No such file or directory
/usr/bin/env: use -[v]S to pass options in shebang lines
env looked for a program literally named bash -euo pipefail. With an absolute path the result is different but still broken:
#!/bin/bash -euo pipefail
/bin/bash: line 0: /bin/bash: ./sheb2.sh: invalid option name
Bash received -euo pipefail as one word and could not parse it. GNU env -S splits the line correctly (#!/usr/bin/env -S bash -euo pipefail worked in the test), but -S is not available everywhere, and every shebang option is ignored when someone runs the file as bash script.sh. In that test, the same file printed flags ehuB when executed directly and flags hB when run with bash. A set line inside the script applies no matter how the script is started, so that is the reliable place:
#!/usr/bin/env bash
set -euo pipefail
Completing the Picture: Two Gaps the Three Options Leave
Gap 1: Command Substitution Ignores set -e
Lesson 119 showed that $( ) runs in a subshell that does not inherit set -e. A function that fails partway through therefore keeps running inside a command substitution:
set -euo pipefail
f() { false; echo "f continued"; }
x=$(f)
echo "x=[$x] without inherit_errexit"
shopt -s inherit_errexit
y=$(f)
echo "not reached"
x=[f continued] without inherit_errexit
The script's exit status was 1. In the first call, false failed but f continued and its last command, echo, succeeded, so the assignment succeeded and the failure was lost. After shopt -s inherit_errexit (available since Bash 4.4), the subshell inherits -e, false ends the subshell with status 1, the assignment y=$(f) fails, and the main script stops.
Gap 2: The ERR Trap Does Not Reach Functions
An ERR trap runs a command whenever a command fails in a way that set -e would act on. It is a convenient place to print where a strict script stopped (lesson 123 covers traps in detail):
set -euo pipefail
trap 'echo "error: line $LINENO: $BASH_COMMAND (status $?)" >&2' ERR
echo start
ls /nonexistent
echo "not reached"
start
ls: cannot access '/nonexistent': No such file or directory
error: line 4: ls /nonexistent (status 2)
$LINENO is the line of the failing command, $BASH_COMMAND is the command text, and $? is its status. The script then ended with status 2.
The trap is not inherited by functions, though. This script failed inside a function and stopped with status 1 without printing anything:
set -euo pipefail
trap 'echo "error: line $LINENO: $BASH_COMMAND (status $?)" >&2' ERR
f() { false; echo "after false in f"; }
f
Adding -E (long form set -o errtrace) makes functions, command substitutions and subshells inherit the ERR trap. With set -Eeuo pipefail the same script printed:
error: line 3: false (status 1)
The Extended Header
A header that closes both gaps looks like this:
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit
trap 'echo "${0##*/}: line $LINENO: \"$BASH_COMMAND\" failed with status $?" >&2' ERR
The three basic options do the real work. -E, inherit_errexit and the trap make the behavior more consistent and the failures easier to locate. inherit_errexit requires Bash 4.4 or later, which matters on older systems (macOS ships Bash 3.2 as /bin/bash, lesson 8).
What About IFS?
Some popular articles add IFS=$'\n\t' to the strict mode header. IFS controls word splitting (lesson 53). Setting it to newline and tab means unquoted expansions no longer split on spaces. In the test:
files="a b.txt c.txt"
for f in $files; do echo "default: [$f]"; done
IFS=$'\n\t'
for f in $files; do echo "newline-tab IFS: [$f]"; done
arr=(x y z)
echo "joined with \"\${arr[*]}\": ${arr[*]}"
read -r a b <<< "first second"
echo "read: a=[$a] b=[$b]"
default: [a]
default: [b.txt]
default: [c.txt]
newline-tab IFS: [a b.txt c.txt]
joined with "${arr[*]}": x
y
z
read: a=[first second] b=[]
The change protects unquoted variables that contain spaces, but it changes other behavior along the way: "${arr[*]}" now joins with a newline, and read no longer splits a line into words on spaces. This is not an error-handling setting, and it is not a substitute for quoting (lesson 55). If a script sets it, every read and every "$*" must be written with the new value in mind. The header in this tutorial leaves IFS alone and relies on quoting.
Patterns That Stay Safe Under Strict Mode
Strict mode stops the script on things that ordinary Bash code does all the time on purpose: a grep that finds nothing, an optional argument that was not given, a counter that starts at zero. Each of these has a standard form that expresses the intent clearly:
set -euo pipefail
printf 'INFO ok\n' > clean.log
count=$(grep -c ERROR clean.log || true)
echo "count=$count"
rc=0
grep -q ERROR clean.log || rc=$?
echo "grep rc=$rc"
i=0
(( ++i ))
echo "i=$i after ((++i))"
j=0
j=$((j + 1))
echo "j=$j"
echo "arg: ${1:-none}"
if [[ -n ${DEBUG-} ]]; then echo debug; else echo "DEBUG not set"; fi
k=0
(( k++ ))
echo "not reached"
count=0
grep rc=1
i=1 after ((++i))
j=1
arg: none
DEBUG not set
The script ended with status 1 at the last arithmetic command. Line by line:
| Situation | Safe form | Why it works |
|---|---|---|
| A count may be zero | n=$(grep -c PAT file || true) | grep -c prints 0 and returns 1; || true accepts that status |
| A status is an answer, not an error | rc=0; cmd || rc=$? | A command on the left of || does not trigger set -e; rc keeps the real status |
| A test decides what to do | if cmd; then ... | Conditions of if, while and until are exempt from set -e |
| Incrementing a counter | (( ++i )) or i=$((i + 1)) | (( i++ )) evaluates to the old value 0, which (( )) reports as status 1 |
| Optional argument | ${1:-default} or ${1:-} | A default makes the expansion never "unbound" |
| Optional environment variable | ${DEBUG-} | Empty if unset, so set -u does not complain |
| Capturing output in a function | local out; out=$(cmd) | local out=$(cmd) returns the status of local (0) and hides the failure |
The last row deserves a test of its own:
set -euo pipefail
f() { local out=$(false); echo "hidden failure, out=[$out]"; }
g() { local out; out=$(false); echo "not reached"; }
f
g
echo "not reached either"
hidden failure, out=[]
The script then stopped with status 1 inside g. Splitting the declaration from the assignment lets the assignment carry the status of the command substitution.
One caution about || true: it accepts every non-zero status, including real errors such as a missing file (status 2 for grep). When the difference matters, save the status and examine it, as the rc=0; cmd || rc=$? row does and as lesson 122 shows with if and case.
Turning Strict Mode Off for a Few Lines
Sometimes a short block needs the default behavior, for example to run a command whose status you want to inspect directly. set +e turns the option off and set -e turns it back on:
set -euo pipefail
set +e
grep -q needle /nonexistent 2>/dev/null
rc=$?
set -e
echo "grep status was $rc, script continues"
false
echo "not reached"
grep status was 2, script continues
The final false stopped the script with status 1, showing that -e was active again.
Saving and Restoring Options Correctly
Code that does not know which options its caller has set, such as a function in a shared library, should save the current settings and restore them instead of assuming. set +o prints the current settings as commands that recreate them:
set -o errexit
set -o nounset
set -o pipefail
The obvious approach captures that output with $( ) and replays it with eval. It has a trap in it:
set -euo pipefail
saved=$(set +o)
set +eu +o pipefail
echo "inside: $-"
eval "$saved"
echo "restored: $- ; $(set -o | grep pipefail)"
inside: hB
restored: huB ; pipefail on
nounset and pipefail came back, but errexit did not: $- shows huB without e. The reason is Gap 1 again. set +o ran inside a command substitution, which does not inherit -e, so it reported set +o errexit. With inherit_errexit on, the subshell sees the real setting:
set -euo pipefail
echo "in \$( ): $(set +o | grep errexit)"
shopt -s inherit_errexit
echo "with inherit_errexit: $(set +o | grep errexit)"
in $( ): set +o errexit
with inherit_errexit: set -o errexit
After adding shopt -s inherit_errexit before the save, the restore printed restored: ehuB ; pipefail on. Another approach avoids the subshell altogether by checking $- for the e flag before changing it:
had_e=0
[[ $- == *e* ]] && had_e=1
set +e
some_command
rc=$?
(( had_e )) && set -e
Where Strict Mode Does Not Belong
Files Meant to Be Sourced
Options are properties of the shell, not of a file. A library loaded with source (lesson 95) that runs set -euo pipefail changes the caller's shell too:
# lib.sh
set -euo pipefail
greet() { echo "hello"; }
# caller.sh
source ./lib.sh
greet
echo "caller flags: $-"
echo "value: $undefined_var"
echo "not reached"
hello
caller flags: ehuB
caller.sh: line 4: undefined_var: unbound variable
caller.sh never asked for strict mode, but it stopped with status 1 on an unset variable. Libraries should leave option choices to the script that loads them; the main script decides.
Interactive Shells
Putting set -e into ~/.bashrc would make the interactive shell exit the first time any command fails, closing the terminal window. In the test, bash -i -c 'set -e; false; echo "after false"' ended with status 1 and never printed the message. Strict mode is for scripts. (set -u alone is less drastic in an interactive shell, as lesson 120 showed, but it still turns every typo in a variable name into an error message.)
A Complete Example
This script counts ERROR lines in every .log file of a directory. It uses the extended header, handles a missing argument and an empty directory as normal cases, and lets strict mode catch real failures:
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit nullglob
trap 'echo "${0##*/}: line $LINENO: \"$BASH_COMMAND\" failed with status $?" >&2' ERR
dir=${1:-}
if [[ -z $dir ]]; then
echo "usage: ${0##*/} DIRECTORY" >&2
exit 2
fi
cd -- "$dir"
logs=(*.log)
if (( ${#logs[@]} == 0 )); then
echo "no .log files in $dir"
exit 0
fi
total=0
for f in "${logs[@]}"; do
n=$(grep -c ERROR -- "$f" || true)
printf '%-10s %s\n' "$f" "$n"
total=$(( total + n ))
done
echo "total errors: $total"
With a logs folder holding app.log (two ERROR lines) and web.log (none), an empty folder logs2, and no folder named missing:
./errcount.sh; echo "status $?"
./errcount.sh logs; echo "status $?"
./errcount.sh logs2; echo "status $?"
./errcount.sh missing; echo "status $?"
usage: errcount.sh DIRECTORY
status 2
app.log 2
web.log 0
total errors: 2
status 0
no .log files in logs2
status 0
./errcount.sh: line 13: cd: missing: No such file or directory
errcount.sh: line 13: "cd -- "$dir"" failed with status 1
status 1
How each piece contributes:
${1:-}lets the script test for a missing argument itself instead of dying with$1: unbound variable, so the user sees a usage message and status 2.nullglob(lesson 52) makes*.logexpand to nothing in an empty folder, so the array is empty rather than holding the literal text*.log.grep -c ... || truetreats a zero count as a normal result. Without|| true,web.logwould have stopped the script.total=$(( total + n ))is an assignment, which never fails because of the arithmetic result, unlike(( total += n ))when the sum is 0.- The failed
cdis a real error.set -estops the script, and theERRtrap adds the line number and the failing command aftercd's own message. -Eandinherit_errexitdo not change the output of this small script, but they keep the behavior the same if the loop body is later moved into a function or a command substitution.
The examples were run with Bash 5.2.21 and GNU coreutils 9.4 on Ubuntu 24.04. Error messages from Bash show the script name and line number when they come from a script file.