Bash Strict Mode, Tested: Six Traps, Each Failing and Then Fixed
Two lines at the top of a script — set -euo pipefail — are the highest-value change you can make to it, and the places where those lines quietly decline to apply are the source of a particular kind of three-hour debugging session. This guide does not re-list the blind spots: a recent guide already covers them well. Instead it builds a small archive script and proves each trap with a test — every trap is demonstrated failing first, then fixed, in a bats suite that runs, under a ShellCheck gate that catches the traps statically.
Written November 6, 2026 · 16 min read
- Why this guide exists when the blind-spot list is already covered
- The header that earns its name
- The ShellCheck gate
- The bats suite
What you will build
A small archive script, archive.sh, that copies a source directory into a dated tarball — plus six pairs of demonstration scripts and a bats suite that proves each trap twice: once failing, once fixed. The project layout is:
strict-mode-traps/
archive.sh # the shipped script, ShellCheck clean
.shellcheckrc # enables check-set-e-suppressed (SC2310)
traps/
trap-01-condition.sh fixed-01-condition.sh
trap-02-local.sh fixed-02-local.sh
trap-03-cmdsubst.sh fixed-03-cmdsubst.sh
trap-04-errtrap.sh fixed-04-errtrap.sh
trap-05-pipefail.sh fixed-05-pipefail.sh
trap-06-arith.sh fixed-06-arith.sh
tests/
traps.bats # 14 tests: 6 failing demos, 6 fixes, 2 end-to-end
| Trap | The failure | The fix |
|---|---|---|
| 1. Function as a condition | The whole body runs with errexit off; a passing tail makes the test pass | Return the verdict explicitly; call the function on its own line |
2. local x=$(...) |
The status is local's (0), not the substitution's |
Split declaration from assignment |
| 3. Command substitution | Errexit is cleared inside $( ) |
shopt -s inherit_errexit (bash 4.4+), or check the value |
4. ERR trap without -E |
The trap is not inherited into functions — silent abort, no location | set -E (errtrace) |
| 5. Pipeline without pipefail | The status is the last command's (0) | set -o pipefail |
6. ((count++)) from zero |
Returns 1 — strict mode kills a healthy script | count=$((count + 1)) |
Tested with GNU bash 5.2.21, ShellCheck 0.11.0, and bats 1.14.0 on Ubuntu 24.04. Bats was installed from the bats-core source release into ~/.local — the box has no sudo access, and the distribution package (bats 1.10.0) needs it. The inherit_errexit fix in trap 3 does not exist in macOS stock bash 3.2.
Why this guide exists when the blind-spot list is already covered
The blind-spot inventory itself is well served. What that guide does not do is test any of it: it never mentions bats, and its ERR-trap section sets a trap without ever discussing -E inheritance. This guide is the other half: a project in which every trap is a test that fails before the fix and passes after it, so a future bash that changes behavior fails loudly here instead of silently in production.
The header that earns its name
The shipped script starts with four lines, and each one is load-bearing:
#!/usr/bin/env bash
set -euo pipefail
set -E
trap 'echo "archive.sh: error at ${BASH_SOURCE##*/}:$LINENO, status $?" >&2' ERR
set -euo pipefail is the strict-mode header: exit on a failed command, exit on an unset variable, and fail a pipeline when any stage fails. set -E is the line most headers omit: it makes the ERR trap inherited by shell functions, command substitutions, and subshells. Without it, the trap in the fourth line never fires inside a function — trap 4 shows exactly that. The trap itself prints the file, the line number, and the status, so a strict-mode abort says where it happened instead of exiting silently.
Two distinctions the manual insists on, and this guide keeps separate throughout: -E (errtrace) inherits the ERR trap; inherit_errexit inherits the errexit setting into command substitutions. They are different flags solving different inheritances, and a header that sets one while needing the other still drops failures. The GNU Bash Reference Manual states both precisely — the -E entry, and the errexit exemption list that defines every trap below.
Trap 1: a function called as a condition
if statement — and the exemption applies to everything inside a called function too, all the way down. Worse, the function returns the status of its last command, so a passing echo at the tail makes the test pass:#!/usr/bin/env bash
set -euo pipefail
check() {
false
echo "still running"
}
if check; then
echo "check passed"
fi
echo "script finished"
Run it:
still running
check passed
script finished
The false did nothing, the function returned the echo's zero, and the script congratulated itself. The probe suite behind this guide confirms the shape on bash 5.2.21: the function body runs with errexit off, and a version whose tail passes reports that the condition passed despite the failure inside.
The fix is not a cleverer flag. It is to write the function so it returns its own verdict explicitly, and to call it on its own line — the form ShellCheck's SC2310 page prescribes:
check() {
if ! false; then
echo "check failed" >&2
return 1
fi
echo "still running"
}
check
echo "check passed"
Now the failing check aborts the script at the standalone call, with check failed on stderr and exit status 1, and check passed never prints. The bats test pins both halves: the buggy script exits 0 and prints check passed; the fixed script exits 1 and prints check failed.
One thing the fix does not do: re-enable -e inside the tested function. The manual states that if a function sets -e while executing in a context where -e is ignored, the setting has no effect until the function call completes. The probe confirms it — a set -e inside the function changes nothing, and inside-after-false still prints. Do not present re-enabling as a fix; it is inert until the compound completes.
Trap 2: local swallowing the exit status
local is itself a command. When you write local out=$(false), the exit status of the line is local's — cheerfully zero — and the failure of the substitution is discarded:masked() {
local out=$(false)
echo "masked: still running"
}
Run it: masked: still running, exit status 0, and the probe behind this guide records local-status=0. The same trap applies to export, declare, and readonly.
The fix is to split the declaration from the assignment, so the status of the line is the substitution's again:
unmasked() {
local out
out=$(false)
echo "unmasked: never reached (out=$out)"
}
The script now aborts at the assignment with exit status 1. ShellCheck catches the buggy form statically: with the gate enabled it reports SC2155, Declare and assign separately to avoid masking return values, on the local out=$(false) line. The shipped archive.sh uses the split form everywhere a value comes from a substitution.
Trap 3: command substitution does not inherit errexit
$( ), errexit is cleared:set -euo pipefail
out=$(false; echo "carried on")
echo "captured: [$out]"
Run it: captured: [carried on], exit status 0. The false changed nothing, and the captured value is the echo's output. The probe records outer-survived x=[inner-survived].
Bash 4.4 added an option to change that:
set -euo pipefail
shopt -s inherit_errexit
out=$(false; echo "should not print")
echo "captured: [$out]"
Now the substitution inherits errexit, the false aborts the subshell, the assignment fails, and the script exits 1 with should not print never printed. The probe confirms it: with inherit_errexit set, the inner line never prints and the exit status is 1.
Two cautions. First, the option does not exist on macOS's stock bash 3.2 — enabling it there reports invalid shell option name. If a script must run on both, do not rely on the option; check the value you got back instead. Second, do not confuse this flag with -E: inherit_errexit inherits the errexit setting, -E inherits the ERR trap. A header with one and not the other still drops a class of failure.
Trap 4: the ERR trap that never fires
-E, the trap is not inherited into functions:set -euo pipefail
trap 'echo "ERR-TRAP: failed at line $LINENO" >&2' ERR
work() {
false
echo "inside-after-false"
}
work
echo "script finished"
Run it: exit status 1, and nothing else. The trap never printed, and inside-after-false never printed either — errexit still exited the script from inside the normally-called function, just silently. The probe records the same shape: exit 1, no ERR-TRAP line. Trap inheritance and errexit are separate, and this run shows both halves at once: the exit works, the report does not.
The fix is one line, set -E, before the trap is set:
set -euo pipefail
set -E
trap 'echo "ERR-TRAP: failed at line $LINENO" >&2' ERR
work() {
false
echo "inside-after-false"
}
work
echo "script finished"
Now the trap fires inside the function and reports ERR-TRAP: failed at line 7 (the false line) before the script exits 1. The manual's wording is exact: if -E is set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment; normally the trap is not inherited in such cases. The shipped archive.sh sets -E before its trap for exactly this reason, and its trap prints the file, line, and status on every abort.
Trap 5: the pipeline that lies
set -euo pipefail
set +o pipefail
false | true
echo "pipeline-status=$? script finished"
Run it: pipeline-status=0 script finished. Every curl ... | jq ... ever written has this shape: the download fails, the next stage gets an empty stream, the pipeline reports success, and the script continues with nothing. The probe records pipeline-status=0 survived.
With pipefail on — it is already on in the header, and the demonstration script turns it off only to show the failure — the pipeline reports the rightmost failure, and errexit aborts the script:
set -euo pipefail
false | true
echo "should not print"
Exit status 1, should not print never printed. The shipped script relies on this in its archive verification: the tar-and-grep pipeline runs under pipefail, so a failed tar is caught even though grep is the last stage.
Trap 6: the false failure
((...)) is a command, and its exit status reflects the value of the expression — non-zero value, status 0; zero value, status 1. Post-increment returns the old value:set -euo pipefail
count=0
((count++))
echo "count=$count script finished"
Run it: exit status 1, and the echo never runs. The script did nothing wrong; the counter started at zero. The probe confirms it on bash 5.2.21: ((count++)) from 0 returns 1.
The fix is one character longer than the problem:
count=0
count=$((count + 1))
echo "count=$count script finished"
An assignment's status is always 0, so the counter increments and the script runs to completion: count=1 script finished. The shipped script's count_files uses the same assignment form, and counts one dot per file from find, so filenames containing newlines cannot miscount the total.
The ShellCheck gate
Install ShellCheck and run it with the optional check-set-e-suppressed check enabled. The check is optional — it is not on by default — and it is enabled by its long name, in .shellcheckrc:
enable=check-set-e-suppressed
or with a directive at the top of a script: #shellcheck enable=check-set-e-suppressed. The rule is SC2310: a function invoked in an if, while, or until condition, negated with !, or on the left-hand side of || or && runs without set -e, however deeply the failure is nested. Its prescribed fix is the one this guide uses throughout — call the function separately, and let the script abort if it fails.
The gate earns its keep on the buggy demos. Run against them, ShellCheck 0.11.0 reports:
In traps/trap-01-condition.sh line 13:
if check; then
^---^ SC2310 (info): This function is invoked in an 'if' condition so set -e will be disabled. Invoke separately if failures should cause the script to exit.
In traps/trap-02-local.sh line 8:
local out=$(false)
^-^ SC2155 (warning): Declare and assign separately to avoid masking return values.
SC2310 fires on exactly the trap it names; SC2155 fires on exactly the local masking. The gate run for this guide: shellcheck archive.sh traps/fixed-*.sh tests/traps.bats exits 0 with no findings, and shellcheck traps/trap-*.sh exits 1 with the two findings above — the gate catches the traps statically, and the shipped script passes it.
The bats suite
Bats is the test harness for bash scripts. Each test runs in its own process, and the run helper invokes a command, saves its exit status in $status and its combined output in $output, and returns 0 — so the assertions decide the verdict, never the harness. A test that only ran a command and trusted its exit code would be the same mistake as the traps it tests.
One test per trap, in both directions:
@test "trap 1 (buggy): function-as-condition passes despite the failure inside" {
run bash "$TRAPS/trap-01-condition.sh"
[ "$status" -eq 0 ]
[[ "$output" == *"still running"* ]]
[[ "$output" == *"check passed"* ]]
}
@test "trap 1 (fixed): the check aborts the script instead of passing" {
run bash "$TRAPS/fixed-01-condition.sh"
[ "$status" -eq 1 ]
[[ "$output" == *"check failed"* ]]
[[ "$output" != *"check passed"* ]]
}
The buggy tests pin the misbehavior on purpose: if a future bash changes how errexit treats a function-as-condition, the test fails loudly here instead of the trap silently disappearing from the guide. The suite also covers the shipped script end to end — archiving a real directory reports the file count and writes the tarball, and a missing source directory fails loudly with not a directory.
Full run, bats 1.14.0:
1..14
ok 1 trap 1 (buggy): function-as-condition passes despite the failure inside
ok 2 trap 1 (fixed): the check aborts the script instead of passing
ok 3 trap 2 (buggy): local masking lets the script finish
ok 4 trap 2 (fixed): split declare/assign aborts on the failure
ok 5 trap 3 (buggy): failure inside $() is invisible, value is the echo
ok 6 trap 3 (fixed): inherit_errexit aborts the substitution
ok 7 trap 4 (buggy): ERR trap never fires inside the function
ok 8 trap 4 (fixed): set -E inherits the trap and reports the line
ok 9 trap 5 (buggy): failed first stage reports success
ok 10 trap 5 (fixed): pipefail reports the failure and aborts
ok 11 trap 6 (buggy): incrementing from zero kills a healthy script
ok 12 trap 6 (fixed): assignment form increments and finishes
ok 13 archive.sh: archives a directory and reports the file count
ok 14 archive.sh: a missing source directory fails loudly
14 tests, 0 failures. Run it yourself with bats tests/traps.bats from the project directory, after shellcheck archive.sh traps/fixed-*.sh tests/traps.bats.
What breaks, and the fix
| Error | Cause | Fix |
| check passed after a failure inside the function | Function called as a condition runs with errexit off for its whole body | Return the verdict explicitly; call the function on its own line |
| Script carries on after local out=$(false) | The status is local's (0) | Split declaration from assignment |
| Captured value is the echo, failure invisible | Errexit is cleared inside $( ) | shopt -s inherit_errexit (bash 4.4+), or check the value |
| Abort with no location, trap never fires | ERR trap not inherited into functions | set -E before setting the trap |
| Pipeline reports success after a failed stage | Status is the last command's | set -o pipefail |
| Script dies on ((count++)) from zero | Post-increment returns the old value (0) as status 1 | count=$((count + 1)) |
| set -e inside a tested function changes nothing | Re-enabling is inert until the compound completes | Do not re-enable; restructure the call instead |
| shopt: inherit_errexit: invalid shell option name | macOS stock bash 3.2 predates the option | Check the captured value instead of relying on the option |
Frequently asked questions
Should every script start with set -euo pipefail?
Every script that runs unattended, yes — that is the point of the header. Do not type it into an interactive shell: the flags apply to the shell that runs them, so a sourced set -e means your terminal exits the next time a command returns non-zero, which in an interactive session is constantly. Scripts, not shells.
Does set -E fix everything the ERR trap misses?
No. -E inherits the trap into functions, command substitutions, and subshells; it does not make errexit itself apply in the exempt contexts. A function called as a condition still runs with errexit off — the trap will report the failure, but nothing aborts unless the function returns its verdict and the caller acts on it. Trap 1 and trap 4 are different fixes for different mechanisms.
Should I just use inherit_errexit everywhere and stop checking values?
Not on any script that must run on macOS stock bash 3.2, where the option does not exist. Where bash 4.4+ is guaranteed, inherit_errexit is the right default — and the value check is still worth keeping for the cases where a substitution legitimately returns an empty result, which no flag can distinguish from a failure.
Is set -e unreliable, then?
No. It is precisely specified, and the specification is not what most people assume. The manual's exemption list is short and exact: conditions, &&/|| lists except the last command, pipelines except the last stage, and !. Every trap in this guide is one entry of that list composed with one other feature — a function, local, a substitution, a trap, a pipeline, an arithmetic command. Learn the list, test the composition, and the behavior stops being surprising.
Where does this sit alongside the blind-spot guides?
Terminal Ninja's Bash Strict Mode: Fail Loudly, Not Silently is the inventory — the four places set -e gives up, the local split, command substitution, and the arithmetic trap, with a runnable playground. This guide is the test project for the same ground: every trap failing first, then fixed, under bats and ShellCheck. Read that guide for the list; run this project to prove it.
Related guides on this site
- Reading an AddressSanitizer Heap-Buffer-Overflow — READ vs WRITE, Traced and Fixed
- Bash Scripting Basics — Variables, Loops, Conditionals, and Functions
- Fix UBSan "Signed Integer Overflow" Runtime Errors — and Why the Optimizer Cares
- Fix ThreadSanitizer "Data Race" Warnings — Read the Two Stacks, Fix the Shared Variable
Source
- GNU Bash Reference Manual, The Set Builtin — the errexit exemption list, the
-E(errtrace) inheritance rule, the inert re-enable rule, and thepipefaildefinition. - terminal.ninja, Bash Strict Mode: Fail Loudly, Not Silently — the blind-spot inventory this guide tests rather than repeats; the Bash 4.4 floor for
inherit_errexit; macOS bash 3.2 predating the option. - ShellCheck, SC2310 — the optional
check-set-e-suppressedrule, theenable=check-set-e-suppressedspelling, and the call-separately fix. - bats-core, Writing tests — the
runhelper,$statusand$output, and the rule that assertions decide the verdict.
Keep Exploring
Paste a [Service] section and get a plain-language verdict on every sandboxing setting it finds.
Paste sshd -G output and get a hardening verdict on the values your server actually runs.
Paste a server block and get WebSocket, TLS, HSTS, and proxy-header verdicts.
Paste a systemd timer expression and get the specific reason it fails, the normalized form, and the past-date traps the built-in check hides.
The full sysadmin hub \u2014 systemd, cgroups, file tools, and measured Linux comparisons.