Exit Codes and Error Propagation

Exit Codes and Error Propagation in Bash: A populated circuit board rolls off the assembly line into the test bay, where it must pass through a row of test…

The Analogy: The Test Bay's Reject-Code Lamps

A populated circuit board rolls off the assembly line into the test bay, where it must pass through a row of test stations bolted end to end: an in-circuit tester that checks each component, a functional tester that powers the board and exercises it, and a final burn-in check. Each station carries a lamp. Green means the board passed that station. If it fails, the lamp glows amber and shows a number: a general-fault code, a wrong-part code, a code that means the station could not even find its test fixture. The number is not decoration -- it tells the technician what went wrong without opening the board.

At the far end of the row a shipping clerk reads exactly one thing: the lamp of the last station the board passed through. If the board made it to the end and that final lamp is green, it is boxed and shipped. A subassembly line that builds daughter-boards and feeds them into the main line does not expose all of its own internal stations to the clerk; it reports upward a single pass-or-fail token for the whole subassembly, and the main line treats that token as if it were one station's verdict.

Because "read only the last lamp" throws away everything the earlier stations saw, a data logger is wired along the bench. It records every station's code, in order, onto a paper strip, so an engineer reviewing a batch can see that station two flagged a fault even though a later station's lamp happened to go green. The line can also be run under a stricter rule: treat the whole row as failed if any station flags a fault, not merely if the last one does. That rule and that strip are what turn a convenient single lamp into a trustworthy record.

The trap is exactly the convenience. Trust the final lamp alone and a board that failed an early station can still ship, because a later station passed it and overwrote the visible verdict. The end-of-line lamp is green, the paperwork says green, and the defect rides out the door. Only the logger's full strip, or the stricter fail-on-any-fault rule, catches it. A single number handed up the line is easy to act on but lossy by design, and the loss is silent unless you have deliberately arranged to see more.


Syntax or Core Structure

Every command a shell runs finishes with an exit status: a single integer from 0 to 255. Zero means success; any non-zero value means failure, and the particular number is the fault code. The status of the most recent command is always available in the special parameter $?. That is the shell's reject-code lamp -- one number that says whether the last thing you did worked.

#!/usr/bin/env bash
true
echo "after true: $?"
false
echo "after false: $?"

Output:

after true: 0
after false: 1

The builtins true and false exist for exactly this: true always exits 0, false always exits 1. The critical thing about $? is that it is overwritten by every command, including the echo that reads it. It reflects only the single most recent command, so if you need a status you must capture it at once.

#!/usr/bin/env bash
false
echo "first read: $?"
echo "second read: $?"

Output:

first read: 1
second read: 0

The first echo reports 1, the status of false. But that echo itself succeeded, so by the time the second echo runs, $? already holds 0 -- the status of the previous echo, not of false. The lamp shows only the last station. To keep a status, assign it immediately: status=$? on the very next line, before any other command can change it.


Technical Depth: Where Codes Come From and How They Travel

The conventional codes

The value 0 for success and non-zero for failure is universal, but several specific numbers carry agreed meanings. Knowing them turns a bare number into a diagnosis.

CodeMeaning
0success
1general failure
2misuse of a shell builtin, or a usage error
126command found but not executable
127command not found
128+Nterminated by signal N (130 from INT, 143 from TERM)
255status out of range, or the result of exit -1

The 127 code is one you will meet often: it means the shell looked for a command and could not find it on PATH.

#!/usr/bin/env bash
nosuchcmd_xyz 2>/dev/null
echo "not found: $?"

Output:

not found: 127

Because the status is a single byte, values wrap modulo 256. Asking for an exit code above 255 does not store the large number; it stores the remainder.

#!/usr/bin/env bash
bash -c 'exit 257'
echo "257 wraps to: $?"

Output:

257 wraps to: 1

Since 257 is 256 plus 1, the stored status is 1. This is why you should keep your own exit codes in the range 0 to 255, and ideally 0 to 125 to avoid colliding with the reserved 126, 127, and 128-plus-signal values.

return versus exit

Inside a function, return N sets the function's status without ending the script -- it is the subassembly reporting its single verdict up to the caller, whose $? then holds that value. exit N ends the whole script and hands N to whatever launched it. Confusing the two is a classic bug: an exit where you meant return kills the entire program.

#!/usr/bin/env bash
check() { return 3; }
check
echo "function returned: $?"

Output:

function returned: 3

The function's return 3 propagates outward: immediately after calling check, $? is 3. A function with no explicit return yields the status of its last command, just as a script with no explicit exit yields the status of its last command.

Pipelines: only the last stage counts

By default a pipeline's exit status is the status of its last command alone -- the end-of-line lamp. Every earlier stage's status is discarded from $?, but the shell keeps them all in the array PIPESTATUS, the data logger's strip.

#!/usr/bin/env bash
false | true
echo "pipeline status: $?"
false | true
echo "each stage: ${PIPESTATUS[@]}"

Output:

pipeline status: 0
each stage: 1 0

The pipeline false | true reports 0, because true is the last stage, even though false failed upstream. PIPESTATUS preserves both: 1 0, left to right. Like $?, it is overwritten by the next pipeline, so capture it at once if you need it.

pipefail: fail on any stage

Setting set -o pipefail changes the rule to the stricter one: the pipeline's status becomes the rightmost non-zero status, so a failure anywhere in the pipeline is visible in $?.

#!/usr/bin/env bash
set -o pipefail
false | true
echo "with pipefail: $?"

Output:

with pipefail: 1

Now the same false | true reports 1, because false failed and pipefail refuses to let the last stage hide it. This is why robust scripts run under set -euo pipefail: without pipefail, a failed curl piped into a successful grep looks like total success, and the defect ships.


Real World Example: A Check Gate That Exits With Its Verdict

Continuous-integration gates live and die by their exit codes: the surrounding system runs your script and branches on $?, shipping on 0 and stopping on anything else. A good gate does two things at once -- it prints a human-readable report of every check, and it exits with a code that summarizes the outcome for the machine. The script below runs three checks on a target file, captures each check's status the instant it fails, and exits with the number of failures, so the exit code itself tells the caller how many things are wrong.

#!/usr/bin/env bash
# gate.sh -- run named checks on a script, report each, exit with the count of failures
set -uo pipefail

fail=0

run_check() {
  local name="$1"; shift
  if "$@"; then
    echo "PASS $name"
  else
    local rc=$?
    echo "FAIL $name (rc=$rc)"
    fail=$((fail + 1))
  fi
}

has_shebang() { head -n 1 "$1" | grep -q '^#!'; }
is_nonempty() { [ -s "$1" ]; }
sets_strict() { grep -q 'set -e' "$1"; }

target="${1:?usage: gate.sh FILE}"

run_check "shebang" has_shebang "$target"
run_check "nonempty" is_nonempty "$target"
run_check "strict-mode" sets_strict "$target"

echo "checks failed: $fail"
exit "$fail"

Point it at a well-formed script:

#!/usr/bin/env bash
set -euo pipefail
echo "deploying"

every check passes and the gate exits 0:

bash gate.sh deploy.sh

Output:

PASS shebang
PASS nonempty
PASS strict-mode
checks failed: 0

Point it at a file with neither a shebang nor a strict-mode line:

just some text
no shebang here

two checks fail, and the gate exits with the failure count, 2:

bash gate.sh plain.txt

Output:

FAIL shebang (rc=1)
PASS nonempty
FAIL strict-mode (rc=1)
checks failed: 2

The mechanism is the lesson in miniature. run_check runs the check as "$@"; if it fails, the very first line of the else is local rc=$?, capturing the status before echo can overwrite it, and fail is incremented. After all three checks, exit "$fail" hands the failure count to the caller as the script's own status. For deploy.sh nothing fails, so the status is 0; for plain.txt two checks fail, so the status is 2. A caller learns both that the gate failed and, from the number, how badly.

Notice the strict-mode line is set -uo pipefail, deliberately without -e. If -e were on, the first failing check would abort the whole script before the remaining checks ran and before the summary printed -- the gate would report far less than it knows. Because this script wants to run every check and then decide, it turns off automatic exit and manages the exit code by hand. This is the right pattern for a program whose entire job is to evaluate other things and report a verdict.

The gate has real limits. Its exit code saturates: because the status is one byte, a run with 256 failing checks would exit 256, which wraps to 0 and falsely signals success -- unlikely with three checks, but a genuine flaw in the design of using a raw count as the code. The sets_strict check is a substring match for set -e, so a file that merely mentions set -e in a comment or a string passes it without actually enabling strict mode, a false positive. And run_check cannot tell a check that failed from a check that is broken: a misspelled check command fails with 127 and is counted as a normal failure. A production gate would cap the exit code, validate more precisely than a substring, and distinguish infrastructure errors from real check failures.


Common Mistakes

  1. Reading $? after another command has run. $? reflects only the single most recent command, so checking it after an intervening echo or [ ... ] reads that command's status instead. Capture it into a variable on the very next line, before anything else executes.
  1. Trusting a pipeline's status without pipefail. By default false | true succeeds, because only the last stage counts. A failed producer piped into a successful consumer looks like success. Enable set -o pipefail when any stage's failure should fail the whole pipeline.
  1. Using exit where you meant return. Inside a function, exit N ends the entire script, not just the function. Use return N to hand a status back to the caller and let the script continue; reserve exit for actually terminating the program.
  1. Returning a status greater than 255. Exit codes are a single byte and wrap modulo 256, so exit 300 stores 44 and exit 256 stores 0 -- silently turning failure into apparent success. Keep codes in 0 to 255, and ideally 1 to 125 for your own errors.
  1. Ending a script with a successful command that masks an earlier failure. A script whose last line is a successful echo "done" exits 0 even if a critical command failed earlier, because the last command sets the status. Check and propagate failures explicitly, or run under set -e.
  1. Treating every failure as the same failure. Collapsing all non-zero codes into "it broke" throws away the diagnosis. A 127 (command not found) and a 1 (the program ran and rejected its input) call for different fixes; branch on the specific code when it matters.
  1. Forgetting that command substitution carries its own status. In output=$(risky), $? afterward is the status of risky, but only until the next command. People check output for emptiness and never look at the status, missing failures that produced partial output.
  1. Not capturing PIPESTATUS immediately. Like $?, the PIPESTATUS array is overwritten by the next pipeline -- and even by a simple command. If you need every stage's status, copy it into your own array on the next line, before any other command runs.
  1. Overloading the exit code as a data channel. The exit code is a status, not a return value. Encoding a computed number, a count that can exceed 255, or a payload into it collides with reserved codes and wraps. Send data to standard output and reserve the exit code for success or failure.

Best Practices

  • Capture the status you care about on the very next line. Both $? and PIPESTATUS are volatile. Write rc=$? (or stages=("${PIPESTATUS[@]}")) immediately after the command, before any test, echo, or assignment can overwrite it.
  • Enable set -o pipefail in scripts that pipe. Combined with set -e, it makes a failure in any pipeline stage fail the script, so a broken producer feeding a happy consumer cannot pass unnoticed. Turn it on at the top with the rest of your strict-mode flags.
  • Return with return from functions, exit with exit from the script. Let functions report a status to their caller and let the top level decide when to terminate. This keeps cleanup traps and later logic from being skipped by a stray exit buried in a helper.
  • Keep your own exit codes in the 1 to 125 range. Avoid 126, 127, and 128-plus-signal, which the shell already assigns specific meanings, and never exceed 255. A small, documented set of codes lets callers branch on the reason for failure.
  • Exit with a meaningful code, not just 0 or 1. When a script can fail for distinct reasons, give each its own code and document them. A caller can then distinguish "config missing" from "network down" without parsing your log messages.
  • Check the codes of commands whose failure matters, and ignore the rest deliberately. For a command you expect to sometimes fail, capture and inspect its status; for one whose failure is harmless, append || true so it does not trip set -e. Make the intent explicit either way.
  • Send data to stdout and status to the exit code. Print results, counts, and payloads to standard output where a caller can read them; reserve the exit code for the single question of whether the run succeeded. Never smuggle a value through the code.
  • Document your exit codes where callers will look. A short table in the script header or usage text -- 0 success, 1 bad usage, 2 missing input, and so on -- turns your codes into a contract that CI pipelines and wrapper scripts can rely on.

Practice Exercises

  1. Capture and branch. Write a script that runs a command passed as arguments, captures its exit code into rc on the next line, and prints ok when rc is 0, not found when it is 127, and failed with N for any other value. Test it with a real command, a missing command, and a command that runs but fails.
  1. Pipeline forensics. Build a three-stage pipeline where the first stage fails, the second succeeds, and the third succeeds. Print the overall $? without pipefail, then copy PIPESTATUS into your own array and print every stage's status. Repeat with set -o pipefail enabled and explain the change in the overall status.
  1. return versus exit. Write a function validate that returns 0 for a non-empty argument and 3 for an empty one, called from a loop over several inputs that tallies failures and continues. Then change the return 3 to exit 3 and observe how the loop and the final tally behave differently; describe why.
  1. A documented gate. Extend the check-gate idea from this lesson: run several named checks, count the failures, and exit with a small documented code (0 all passed, 1 some checks failed, 2 the target file was missing entirely). Add a usage comment listing the codes, and verify each code is produced by the matching scenario.