Testing Error Paths and Exit Codes
Most tests people write for a script check the happy path: correct input goes in, the expected result comes out. But a script spends most of its real life dealing with things that go wrong: a missing file, a typo in an option, a full disk, a server that does not answer. The code that handles these situations is called the script's error paths, and it is the code most likely to be broken, because it runs rarely and nobody notices when it misbehaves until the day it matters.
For a shell script, the most important part of an error path is its exit code (also called exit status). Other programs, cron, CI systems and calling scripts do not read the script's messages; they read the number it returns. A script that prints "ERROR" and then exits with status 0 tells every caller that it succeeded. Testing error paths therefore means checking three things for each failure: the exit code is the documented one, the message goes to standard error and says what went wrong, and the state left behind is safe, with no half-written files and no changes that should not have happened.
This lesson shows how to design exit codes that can be tested, how to provoke each failure on purpose, and how to check status, stderr and leftover state, first with plain Bash and then with Bats (lesson 185).
Exit Codes: A Quick Reference
Every command finishes with a number from 0 to 255. Zero means success; anything else means failure (lesson 116). Some values have fixed meanings that tests regularly encounter:
| Status | Meaning |
|---|---|
| 0 | success |
| 1 | general failure; also "no match" for grep and "files differ" for diff and cmp |
| 2 | usage error by convention; grep also uses 2 for real errors such as an unreadable file |
| 124 | the command was stopped by timeout (lesson 142) |
| 126 | the file was found but could not be executed (for example, missing execute permission) |
| 127 | command not found |
| 128 + N | the command was killed by signal N: 130 for SIGINT (Ctrl+C), 143 for SIGTERM |
These values can be observed directly:
nosuchcmd 2>/dev/null; echo "missing command -> $?"
touch notexec; ./notexec 2>/dev/null; echo "not executable -> $?"
timeout 1 sleep 5; echo "timeout -> $?"
sleep 5 & pid=$!; kill -TERM "$pid"; wait "$pid"; echo "killed by TERM -> $?"
grep -q x /nonexistent; echo "grep, missing file -> $?"
echo abc | grep -q x; echo "grep, no match -> $?"
missing command -> 127
not executable -> 126
timeout -> 124
killed by TERM -> 143
grep: /nonexistent: No such file or directory
grep, missing file -> 2
grep, no match -> 1
Notice how grep distinguishes "nothing found" (1) from "something is broken" (2). Good scripts make the same kind of distinction, and tests make sure the distinction survives future changes.
Values Outside 0 to 255
An exit status is stored in 8 bits, so Bash keeps only the remainder after dividing by 256. A script that computes its exit code, for example by counting errors, can accidentally report success:
bash -c 'exit 256'; echo "exit 256 -> $?"
bash -c 'exit 300'; echo "exit 300 -> $?"
bash -c 'exit -1'; echo "exit -1 -> $?"
exit 256 -> 0
exit 300 -> 44
exit -1 -> 255
A script that runs exit "$error_count" returns 0 after exactly 256 errors. Cap such values, for example with (( error_count > 0 )) && exit 1, and test the boundary if the code computes its status.
Designing Exit Codes That Can Be Tested
Before an error path can be tested, the script must say what it promises. The script used in this lesson validates a CSV sales report and publishes it into a directory. Its header comment documents one exit code per kind of failure:
#!/usr/bin/env bash
#
# publish-report.sh - validate a CSV sales report and publish it into a directory
#
# Usage: publish-report.sh [-f] REPORT.csv DEST_DIR
#
# Exit status:
# 0 report published
# 2 usage error (wrong number of arguments or unknown option)
# 3 report missing or unreadable
# 4 report invalid (wrong header or no data rows)
# 5 destination not writable, or copying failed
# 6 report already published (use -f to replace it)
set -euo pipefail
readonly EX_USAGE=2 EX_NOINPUT=3 EX_DATAERR=4 EX_CANTCREAT=5 EX_EXISTS=6
readonly HEADER='date,region,amount'
die() {
local code=$1
shift
printf '%s: %s\n' "${0##*/}" "$*" >&2
exit "$code"
}
usage() { printf 'Usage: %s [-f] REPORT.csv DEST_DIR\n' "${0##*/}" >&2; }
force=0
while getopts ':f' opt; do
case $opt in
f) force=1 ;;
*) usage; exit "$EX_USAGE" ;;
esac
done
shift $((OPTIND - 1))
(( $# == 2 )) || { usage; exit "$EX_USAGE"; }
report=$1 dest=$2
[[ -f $report && -r $report ]] || die "$EX_NOINPUT" "cannot read report: $report"
first=""
IFS= read -r first < "$report" || true # an empty file has no first line
[[ $first == "$HEADER" ]] || die "$EX_DATAERR" "bad header in $report (expected '$HEADER')"
rows=$(( $(wc -l < "$report") - 1 ))
(( rows > 0 )) || die "$EX_DATAERR" "no data rows in $report"
[[ -d $dest && -w $dest ]] || die "$EX_CANTCREAT" "destination not writable: $dest"
target=$dest/${report##*/}
if [[ -e $target ]] && (( ! force )); then
die "$EX_EXISTS" "already published: $target (use -f to replace it)"
fi
tmp=$(mktemp "$dest/.publish.XXXXXX") || die "$EX_CANTCREAT" "cannot create a temporary file in $dest"
trap 'rm -f "$tmp"' EXIT # never leave a half-written file behind
cp -- "$report" "$tmp" || die "$EX_CANTCREAT" "copy failed: $report -> $tmp"
mv -f -- "$tmp" "$target" || die "$EX_CANTCREAT" "cannot move the report into place: $target"
trap - EXIT
printf 'published %s (%d rows)\n' "$target" "$rows"
Several design choices make this script easy to test:
- Named constants for exit codes.
EX_USAGE,EX_NOINPUTand the others make everyexitself-explanatory and keep the numbers in one place. The names follow the style of the traditional BSDsysexits.hcodes, but the values here are the script's own, chosen to be small and documented. What matters is that they are distinct and written down. - One
diefunction. Every failure goes throughdie, which printsscriptname: messageto standard error and exits with the given code. Tests can rely on a single message format. - Messages on stderr, results on stdout. A caller that captures the script's output receives only the success message, never an error mixed into data.
- Write to a temporary file, then rename. The report is copied to a temporary file in the destination directory and moved into place only when the copy succeeded. A
trap ... EXIT(lesson 124) deletes the temporary file on every failure. The visible result is all or nothing, which is exactly what a test can check. - Explicit handling of the empty file.
readfails at end of file, which would stop aset -escript with status 1 and no message.|| trueturns that into the documented status 4.
Running it by hand shows the contract in action:
$ ./bin/publish-report.sh; echo "status $?"
Usage: publish-report.sh [-f] REPORT.csv DEST_DIR
status 2
$ printf 'day;x\n' > /tmp/bad.csv
$ ./bin/publish-report.sh /tmp/bad.csv /tmp; echo "status $?"
publish-report.sh: bad header in /tmp/bad.csv (expected 'date,region,amount')
status 4
Capturing Exit Codes Correctly
Testing exit codes in Bash is easy to get subtly wrong, because $? is fragile. It always holds the status of the most recent command, so it must be read immediately. Four traps catch people regularly.
Anything in between overwrites $?. An echo or [ ... ] placed between the command and the check reports its own status instead. Save it right away:
"$PUBLISH" "$report" "$dir"
status=$? # the very next command
A pipeline reports its last command. cmd | tee log returns the status of tee, which almost always succeeds. PIPESTATUS holds every element's status, and set -o pipefail makes the pipeline fail when any part fails (lesson 120):
false | true; echo "false | true -> $?"
false | true; echo "PIPESTATUS: ${PIPESTATUS[*]}"
false | true -> 0
PIPESTATUS: 1 0
local hides the status of a command substitution. local x=$(cmd) returns the status of local, which is 0. Declare first, assign second:
f() { local x=$(false); echo "local masked -> $?"; }; f
g() { local x; x=$(false); echo "separate -> $?"; }; g
local masked -> 0
separate -> 1
! turns any failure into success. ! cmd is useful for "this must fail", but it cannot distinguish status 2 from status 4. An error-path test that only checks "it failed" passes even when the script fails for the wrong reason, for instance with 127 because a command was misspelled. Check the exact code whenever the script documents one.
set -e adds one more complication: in a test script with set -e, a failing command under test would stop the whole test before its status could be checked. Either leave set -e off in the test driver, or run the command where set -e does not apply, such as in an if condition or with || status=$?.
Testing Error Paths with Plain Bash
A test framework is convenient but not required. A small function that runs a command, saves $? and compares it with the expected value is enough for a smoke test that can run anywhere:
#!/usr/bin/env bash
# smoke.sh - check the exit statuses of publish-report.sh without any test framework
PUBLISH=${PUBLISH:-./bin/publish-report.sh}
failures=0
# expect_status WANT DESCRIPTION -- COMMAND...
expect_status() {
local want=$1 desc=$2 got
shift 3 # drop WANT, DESCRIPTION and the -- separator
"$@" > /dev/null 2>&1
got=$? # read $? immediately, before anything else runs
if (( got == want )); then
printf 'PASS %-34s status %d\n' "$desc" "$got"
else
printf 'FAIL %-34s expected %d, got %d\n' "$desc" "$want" "$got"
failures=$((failures + 1))
fi
}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mkdir "$work/out"
printf 'date,region,amount\n2026-11-30,south,1250\n' > "$work/ok.csv"
printf 'date,region,amount\n' > "$work/empty.csv"
expect_status 2 "no arguments" -- "$PUBLISH"
expect_status 3 "missing report" -- "$PUBLISH" "$work/missing.csv" "$work/out"
expect_status 4 "header only" -- "$PUBLISH" "$work/empty.csv" "$work/out"
expect_status 5 "destination is a file" -- "$PUBLISH" "$work/ok.csv" "$work/ok.csv"
expect_status 0 "valid report" -- "$PUBLISH" "$work/ok.csv" "$work/out"
expect_status 6 "second publish refused" -- "$PUBLISH" "$work/ok.csv" "$work/out"
(( failures == 0 )) || { echo "$failures check(s) failed"; exit 1; }
echo "all checks passed"
$ ./test/smoke.sh
PASS no arguments status 2
PASS missing report status 3
PASS header only status 4
PASS destination is a file status 5
PASS valid report status 0
PASS second publish refused status 6
all checks passed
How it works:
- The
--separator makes calls easy to read: everything after it is the command.shift 3removes the expected status, the description and the separator, leaving the command in"$@", which runs it with all arguments preserved. got=$?comes directly after the command, as discussed above. The script deliberately does not useset -e, because the commands under test are supposed to fail.- Every test case uses its own scratch directory created with
mktemp -dand removed by a trap, so the tests never touch real data. - The last two checks depend on each other: the first publish succeeds and the second must then fail with status 6. Ordering like this is acceptable in a short smoke test; in a larger suite, each test should create its own state, as the Bats version below does.
- The smoke test itself exits non-zero when any check fails, so a CI system (lesson 177) can run it like any other command.
To see that the test protects the contract, change the script's "no data rows" error from die "$EX_DATAERR" to die 1, a typical refactoring slip. The message is still correct, but the smoke test notices the wrong code:
$ PUBLISH=/tmp/mutated-publish-report.sh ./test/smoke.sh
PASS no arguments status 2
PASS missing report status 3
FAIL header only expected 4, got 1
PASS destination is a file status 5
PASS valid report status 0
PASS second publish refused status 6
1 check(s) failed
Testing Error Paths with Bats
Bats makes error-path tests shorter and adds the ability to check standard output and standard error separately. Two features of its run command are made for this lesson's topic (they require Bats 1.5.0 or later, which is why the file starts with bats_require_minimum_version 1.5.0):
run -N commandfails the test unless the command exits with exactly status N.run -0demands success;run !demands any non-zero status.run --separate-stderr commandputs standard output in$outputand standard error in$stderr. Without it, both streams are mixed in$output, which hides a script that prints errors on the wrong stream.
The complete test file covers every documented exit code:
#!/usr/bin/env bats
#
# Error-path tests for bin/publish-report.sh: every documented exit status,
# the message on stderr, and the state of the destination afterwards.
bats_require_minimum_version 1.5.0
setup() {
PUBLISH="$BATS_TEST_DIRNAME/../bin/publish-report.sh"
SRC="$BATS_TEST_TMPDIR/sales.csv"
OUT="$BATS_TEST_TMPDIR/public"
mkdir "$OUT"
printf 'date,region,amount\n2026-11-30,south,1250\n2026-11-30,north,980\n' > "$SRC"
}
# --- usage errors: status 2 -------------------------------------------------
@test "no arguments: status 2, usage on stderr, nothing on stdout" {
run -2 --separate-stderr "$PUBLISH"
[ -z "$output" ]
[[ $stderr == "Usage: publish-report.sh [-f] REPORT.csv DEST_DIR" ]]
}
@test "unknown option: status 2" {
run -2 --separate-stderr "$PUBLISH" -x "$SRC" "$OUT"
[[ $stderr == Usage:* ]]
}
# --- input errors: status 3 and 4 ------------------------------------------
@test "missing report: status 3 with the file name in the message" {
run -3 --separate-stderr "$PUBLISH" "$BATS_TEST_TMPDIR/nope.csv" "$OUT"
[ "$stderr" = "publish-report.sh: cannot read report: $BATS_TEST_TMPDIR/nope.csv" ]
}
@test "unreadable report: status 3" {
[[ $EUID -ne 0 ]] || skip "root can read any file"
chmod 000 "$SRC"
run -3 "$PUBLISH" "$SRC" "$OUT"
}
@test "wrong header: status 4" {
printf 'day;region;amount\n2026-11-30;south;1250\n' > "$SRC"
run -4 --separate-stderr "$PUBLISH" "$SRC" "$OUT"
[[ $stderr == *"bad header"* ]]
}
@test "header without data rows: status 4" {
printf 'date,region,amount\n' > "$SRC"
run -4 --separate-stderr "$PUBLISH" "$SRC" "$OUT"
[[ $stderr == *"no data rows"* ]]
}
@test "empty file: status 4, not a crash" {
: > "$SRC"
run -4 "$PUBLISH" "$SRC" "$OUT"
}
# --- destination errors: status 5 and 6 ------------------------------------
@test "destination is a file, not a directory: status 5" {
run -5 "$PUBLISH" "$SRC" "$SRC"
[[ $output == *"destination not writable"* ]]
}
@test "read-only destination: status 5" {
[[ $EUID -ne 0 ]] || skip "root can write to read-only directories"
chmod 555 "$OUT"
run -5 "$PUBLISH" "$SRC" "$OUT"
}
@test "already published: status 6 and the old copy is untouched" {
echo "old version" > "$OUT/sales.csv"
run -6 "$PUBLISH" "$SRC" "$OUT"
[ "$(cat "$OUT/sales.csv")" = "old version" ]
}
@test "-f replaces an existing copy: status 0" {
echo "old version" > "$OUT/sales.csv"
run -0 "$PUBLISH" -f "$SRC" "$OUT"
cmp -s "$SRC" "$OUT/sales.csv"
}
@test "failed copy: status 5, no target and no temporary file left behind" {
load mocks
mock_setup
mock cp 1
run -5 --separate-stderr "$PUBLISH" "$SRC" "$OUT"
[[ $stderr == *"copy failed"* ]]
[ ! -e "$OUT/sales.csv" ]
[ -z "$(ls -A "$OUT")" ]
}
# --- the success path, for contrast ----------------------------------------
@test "valid report: status 0, message on stdout, stderr empty" {
run -0 --separate-stderr "$PUBLISH" "$SRC" "$OUT"
[ "$output" = "published $OUT/sales.csv (2 rows)" ]
[ -z "$stderr" ]
cmp -s "$SRC" "$OUT/sales.csv"
}
How the Tests Provoke Each Failure
Every error path needs a way to make it happen on demand. The test file uses four techniques, which together cover most real scripts:
- Bad arguments. Calling the script with too few arguments or an unknown option is the simplest failure to provoke, and the usage path is one of the most frequently broken.
- Crafted input files. Each test writes exactly the content it needs into
$BATS_TEST_TMPDIR: a wrong header, a header with no rows, an empty file. Boundary cases like the empty file are where scripts most often crash instead of failing cleanly. - Manipulated file system state. A destination that is a regular file, a file that already exists, or permissions removed with
chmod. - Fake commands. Some failures cannot be produced with files alone. A copy that fails halfway through, for example because the disk filled up, is hard to arrange for real. The test uses the mock library from lesson 186 to replace
cpwith a fake that exits with status 1, which drives the script into its cleanup code.
Permissions and the Root User
The tests for an unreadable report and a read-only destination are skipped when the tests run as root. The superuser ignores ordinary read and write permissions, so chmod 000 does not make a file unreadable for root, and the script would correctly succeed. Without the skip, these tests would fail in Docker containers and CI jobs that run as root, for reasons that have nothing to do with the script. Bats reports skipped tests separately, so they remain visible:
ok 4 unreadable report: status 3 # skip (root can read any file)
When the same suite runs as an ordinary user, both tests execute and pass. If permission paths matter, run the suite at least once as a non-root user, for instance with runuser -u nobody in a container.
Checking the State Left Behind
The status code alone does not prove that an error path is safe. Three tests check the file system after the failure:
- "already published" verifies that the existing copy still says
old version. A script that refused with status 6 but had already overwritten the file would pass a status-only test. - "failed copy" verifies that the target does not exist and that
ls -A "$OUT"prints nothing, which means no hidden.publish.XXXXXXfile remains. This is the test that guards thetrapcleanup. - "valid report", the success test, uses
cmp -sto prove that the published file is byte-for-byte identical to the source.
Running the Suite
As in lessons 185 and 186, Bats could not be installed where this lesson was prepared, because the environment had no network access. The tests were executed with Bash 5.2 using a small stand-in harness that implements the Bats features used here (run -N, run !, --separate-stderr, skip, load, setup) and prints TAP output in the format of bats --tap. The run was done as root, so the two permission tests were skipped; a second run as the unprivileged user nobody executed and passed them.
$ bats --tap test/publish-report.bats
1..13
ok 1 no arguments: status 2, usage on stderr, nothing on stdout
ok 2 unknown option: status 2
ok 3 missing report: status 3 with the file name in the message
ok 4 unreadable report: status 3 # skip (root can read any file)
ok 5 wrong header: status 4
ok 6 header without data rows: status 4
ok 7 empty file: status 4, not a crash
ok 8 destination is a file, not a directory: status 5
ok 9 read-only destination: status 5 # skip (root can write to read-only directories)
ok 10 already published: status 6 and the old copy is untouched
ok 11 -f replaces an existing copy: status 0
ok 12 failed copy: status 5, no target and no temporary file left behind
ok 13 valid report: status 0, message on stdout, stderr empty
To confirm that test 12 really guards the cleanup, the line trap 'rm -f "$tmp"' EXIT was removed from the script. The script still exits with status 5 and prints the right message, so a status-only test would pass. The state check catches the leftover temporary file:
not ok 12 failed copy: status 5, no target and no temporary file left behind
# (in test file test/publish-report.bats, line 91)
# `[ -z "$(ls -A "$OUT")" ]' failed
Testing Signals and Timeouts
Scripts that run for a long time also have error paths triggered from outside: a user presses Ctrl+C, a service manager sends SIGTERM, or a timeout wrapper stops them. The same approach applies. Start the script in the background, send the signal, collect the status with wait, and inspect the state:
./long-job.sh "$workdir" &
pid=$!
sleep 1 # give the script time to start working
kill -TERM "$pid"
wait "$pid"
status=$?
(( status == 143 )) # 128 + 15: terminated by SIGTERM
[ -z "$(ls -A "$workdir/tmp")" ] # the trap removed the temporary files
If the script catches the signal with trap ... TERM and exits on its own, it decides its exit code itself; many scripts deliberately exit with 128 + signal number so that callers can still tell that it was interrupted (lesson 141). Whichever convention the script follows, the test writes it down. Avoid long sleep calls in tests: wait for a file that the script creates when it is ready, or replace sleep with a fake as in lesson 186.
Choosing Which Error Paths to Test
A script usually has more possible failures than are worth a test each. A useful order of priority:
- Every documented exit code at least once. If the header comment promises a code, a test should prove it.
- Paths that protect data: refusing to overwrite, cleaning up partial output, rolling back. These are the failures whose bugs cause real damage.
- Boundary inputs: empty files, a header without rows, a single line without a trailing newline, file names with spaces (lesson 111).
- Failures of external commands that the script handles explicitly, provoked with fakes.
The next lesson moves from testing to portability: how to write scripts that behave the same way on different systems and shells, including the systems where the error paths in this lesson were never exercised.