Exit Status and Command Chaining

Exit Status and Command Chaining in Bash: --- A parcel depot gives every driver a handheld scanner and a laminated card of two-digit codes.


The Analogy: The Courier Depot's Exception Codes

A parcel depot gives every driver a handheld scanner and a laminated card of two-digit codes. Code 00 means delivered. Everything else is a numbered reason: 12 for premises closed, 21 for refused at the door, 34 for address not found, 47 for parcel damaged in transit. The driver scans the parcel at each stop and keys one code. That code is the entire report. No photograph, no sentence, no phone call -- one number, and it is the only thing that travels back to the depot from a stop the office cannot see.

The night sort is built on a single question about that number: was it zero? Zero and the parcel is closed off. Anything else and the parcel drops into the exceptions bay for a human. What the sort never distinguishes is the two very different reasons a code can be non-zero. Code 21 means the delivery genuinely happened and genuinely failed -- someone stood at the door and said no. But there is also code 91, which means the scanner could not read the barcode at all, so nobody knows whether the parcel was delivered, refused, or still in the van. One is an answer; the other is the absence of an answer. Both are simply "not zero" to the machine that sorts them.

The handheld holds one code at a time. Key a code at the next stop and the previous one is gone -- it has been sent, but the display now shows only the latest. This matters because the office reads the display, not the history, whenever it wants a quick verdict on how a round went. Everything the driver does that ends in a scan overwrites that display, including the depot's own housekeeping barcodes: the fuel-card scan, the vehicle check-in, the "round complete" plate by the loading door. Those all return 00, because they all worked.

The failure mode is the last scan of the day. A driver finishes a round in which the third stop returned code 12, drives back, and scans the "round complete" plate on the way in, which returns 00. The supervisor glances at the handheld, sees 00, and files the round as clean. Nobody lied and nothing malfunctioned -- the display is showing exactly what it is designed to show, the code from the most recent scan. The code 12 was real, was recorded, and was true, and it is now invisible to the only check anyone actually performs. The parcel sits in the van overnight and the customer calls at nine the next morning.


Syntax or Core Structure

Every command bash runs leaves behind exactly one number, from 0 to 255, and $? holds the one from the most recent command. Zero means success. Every non-zero value means something went wrong, and which value it is is up to the command.

#!/usr/bin/env bash
probe() {
  printf 'probe %s running\n' "$1"
  return "$2"
}
probe ok 0
printf 'status after probe ok: %d\n' "$?"
probe bad 4
printf 'status after probe bad: %d\n' "$?"
printf 'status after that printf: %d\n' "$?"
grep -q nothing /dev/null
printf 'grep found nothing, status: %d\n' "$?"
[ 5 -gt 9 ]
printf 'the test command itself, status: %d\n' "$?"

Output:

probe ok running
status after probe ok: 0
probe bad running
status after probe bad: 4
status after that printf: 0
grep found nothing, status: 1
the test command itself, status: 1

Line five of that output is the handheld display. The printf that reported status 4 succeeded, so by the time the next printf asks $? the answer is 0 -- the 4 is gone, one command later. $? is not a record of the last failure; it is the status of the last command, whatever that command was.

The last two blocks are worth pausing on. grep -q returning 1 is not an error: 1 is how grep says "no match", and it is the answer the caller asked for. And [ 5 -gt 9 ] shows that [ is an ordinary command that happens to return 1 when its comparison is false. Bash has no boolean type in conditionals -- if and while run a command and look at the number it leaves.

That number is also what the chaining operators read.

#!/usr/bin/env bash
step() { printf '  %s\n' "$1"; return "$2"; }
printf '%s\n' '-- && runs the right side only on success'
step first 0 && step second 0
printf 'chain status %d\n' "$?"
printf '%s\n' '-- && stops on failure'
step first 4 && step second 0
printf 'chain status %d\n' "$?"
printf '%s\n' '-- || runs the right side only on failure'
step first 4 || step recover 0
printf 'chain status %d\n' "$?"
printf '%s\n' '-- the a && b || c trap: b fails, so c runs too'
step first 0 && step second 7 || step cleanup 0
printf 'chain status %d\n' "$?"
printf '%s\n' '-- ! inverts the status to 0 or 1'
! step first 4
printf 'negated 4 gives %d\n' "$?"
! step first 0
printf 'negated 0 gives %d\n' "$?"

Output:

-- && runs the right side only on success
  first
  second
chain status 0
-- && stops on failure
  first
chain status 4
-- || runs the right side only on failure
  first
  recover
chain status 0
-- the a && b || c trap: b fails, so c runs too
  first
  second
  cleanup
chain status 0
-- ! inverts the status to 0 or 1
  first
negated 4 gives 0
  first
negated 0 gives 1

The fourth block is the trap that catches everyone. a && b || c is not an if-then-else. It reads left to right as (a && b) || c, so c runs whenever the pair fails -- which includes the case where a succeeded and b failed. Here first passed, second returned 7, and cleanup ran anyway. Worse, the chain's own status is now cleanup's 0, so the caller sees a clean run. Use a real if when the two branches are genuinely alternatives.


Technical Depth: Which Number Arrives, and When It Is Lost

The conventional values

Bash and the wider Unix world reserve a handful of numbers. A command's own failures should stay well clear of them.

StatusMeaningWho sets it
0successthe command
1general failure, or "no" from a testthe command
2commonly a usage errorby convention only
126found, but could not be executedthe shell
127command not foundthe shell
128 plus Nkilled by signal Nthe shell, reporting the child
130killed by SIGINT, which is signal 2the shell
143killed by SIGTERM, which is signal 15the shell
255out of range, or a specific tool's own choicethe command
#!/usr/bin/env bash
printf '%s\n' '-- 127 means the shell could not find the command'
no-such-command-here
printf 'status %d\n' "$?"
printf '%s\n' '-- 126 means it was found but could not be run'
mkdir -p adir
./adir
printf 'status %d\n' "$?"
printf '%s\n' '-- 128 plus the signal number when a child is killed'
bash -c 'kill -TERM $$'
printf 'TERM is signal 15, status %d\n' "$?"
bash -c 'kill -INT $$'
printf 'INT is signal 2, status %d\n' "$?"
printf '%s\n' '-- exit truncates to the low eight bits'
bash -c 'exit 256'
printf 'exit 256 arrives as %d\n' "$?"
bash -c 'exit 257'
printf 'exit 257 arrives as %d\n' "$?"

Output:

-- 127 means the shell could not find the command
status 127
-- 126 means it was found but could not be run
status 126
-- 128 plus the signal number when a child is killed
TERM is signal 15, status 143
INT is signal 2, status 130
-- exit truncates to the low eight bits
exit 256 arrives as 0
exit 257 arrives as 1

Those are the stdout lines only. The run also produced three lines on stderr -- command not found, Is a directory, and bash's own Terminated notification for the signalled child -- which is why the block above is quiet where you might expect noise.

The truncation at the end is the reason a status is never a return value. exit 256 arrives as 0, meaning a script that computes a count and exits with it reports success the moment the count reaches 256. Statuses are one byte. Anything larger, or negative, wraps.

The distinction the codes are making

126 and 127 come from the shell, not from your program, and they mean the program never ran. Grouping them with a genuine non-zero is the scanner's code 91 problem: a script that only asks "was it zero?" cannot tell "the check said no" from "the check was never performed". Any runner that reports on other commands should treat 126 and 127 as a separate class.

exit and return with no argument

Both default to the status of the last command that ran, which is convenient and occasionally disastrous.

#!/usr/bin/env bash
cleanup() { printf 'cleanup ran\n'; }
trap cleanup EXIT
bash -c 'exit 4'
exit

Output:

cleanup ran
exit with no argument gave 4

The second line was printed by the caller. A bare exit passed the 4 through, which is usually what you want -- but note that the printf inside cleanup did not change it. Bash preserves the pending exit status across an EXIT trap unless the trap itself calls exit, so a trap that ends in a successful command does not silently zero your status. A trap that ends in exit 0, on the other hand, does exactly that.

Drop the trap and the masking is immediate:

#!/usr/bin/env bash
bash -c 'exit 4'
printf 'done\n'

Output:

done
a trailing printf hid the 4 and gave 0

Again the second line comes from the caller. A script's exit status, with no explicit exit, is the status of its last command -- and a friendly closing message is a command. This is the "round complete" scan.

set -e and the list of things it does not catch

set -e asks bash to exit when a command fails. The rule has so many documented exceptions that treating it as a safety net is itself a hazard.

#!/usr/bin/env bash
set -e
bad() { return 5; }
printf '%s\n' '-- set -e ignores a failure in an if condition'
if bad; then printf 'unreachable\n'; else printf 'if condition failed, still running\n'; fi
printf '%s\n' '-- set -e ignores the left side of &&'
bad && printf 'unreachable\n'
printf 'after the && chain, still running\n'
printf '%s\n' '-- set -e ignores a negated command'
! bad
printf 'after ! bad, still running\n'
printf '%s\n' '-- set -e ignores every stage of a pipeline but the last'
bad | cat
printf 'after the pipeline, still running, status %d\n' "$?"
printf '%s\n' '-- and now a bare failure'
bad
printf 'unreachable\n'

Output:

-- set -e ignores a failure in an if condition
if condition failed, still running
-- set -e ignores the left side of &&
after the && chain, still running
-- set -e ignores a negated command
after ! bad, still running
-- set -e ignores every stage of a pipeline but the last
after the pipeline, still running, status 0
-- and now a bare failure
script exited 5

The last line is the caller reporting the script's status; neither unreachable line was ever printed. Four failures of the same function were ignored and the fifth, identical in every respect except its syntactic position, terminated the script. The exceptions are not arbitrary -- a command whose status is being tested is not considered to have failed -- but they mean set -e protects only bare commands in a statement position. The status that escapes is the function's own 5, not 1.

pipefail and PIPESTATUS

A pipeline's status is its last stage's, so a failing producer is invisible. set -o pipefail changes that, and PIPESTATUS records every stage.

#!/usr/bin/env bash
printf '%s\n' '-- a pipeline reports only its last stage'
bash -c 'printf "one line\n"; exit 6' | cat
printf 'status %d, PIPESTATUS %s\n' "$?" "${PIPESTATUS[*]}"
printf '%s\n' '-- with pipefail it reports a failing stage'
set -o pipefail
bash -c 'printf "one line\n"; exit 6' | cat
printf 'status %d, PIPESTATUS %s\n' "$?" "${PIPESTATUS[*]}"
printf '%s\n' '-- two failing stages: the last non-zero one wins'
bash -c 'exit 6' | bash -c 'cat >/dev/null; exit 9'
printf 'status %d, PIPESTATUS %s\n' "$?" "${PIPESTATUS[*]}"
printf '%s\n' '-- PIPESTATUS is overwritten by the very next command'
bash -c 'exit 6' | cat
true
printf 'after true, PIPESTATUS is %s\n' "${PIPESTATUS[*]}"

Output:

-- a pipeline reports only its last stage
one line
status 0, PIPESTATUS 6 0
-- with pipefail it reports a failing stage
one line
status 6, PIPESTATUS 6 0
-- two failing stages: the last non-zero one wins
status 9, PIPESTATUS 6 9
-- PIPESTATUS is overwritten by the very next command
after true, PIPESTATUS is 0

Read the third block carefully, because it is the detail most people get backwards: pipefail reports the status of the last stage to exit non-zero, not the first. Stage one exited 6 and stage two exited 9, and the pipeline reported 9. The fourth block is the handheld display again -- PIPESTATUS is rebuilt by every command, and true reduced a two-element array to a single 0. Capture it into your own variable on the line immediately after the pipeline or it is gone.

trap ... ERR and trap ... EXIT

An ERR trap fires wherever set -e would exit; an EXIT trap fires however the script ends.

#!/usr/bin/env bash
set -e
trap 'printf "ERR trap: status %d at line %d\n" "$?" "$LINENO"' ERR
trap 'printf "EXIT trap: final status %d\n" "$?"' EXIT
printf 'starting\n'
false
printf 'unreachable\n'

Output:

starting
ERR trap: status 1 at line 6
EXIT trap: final status 1
the script exited 1

Both traps saw the real status, the ERR trap reported the line, and the script still exited 1 -- the printing did not overwrite the pending status. Because ERR shares set -e's exception list, it stays silent in exactly the four positions shown earlier. Use set -E (set -o errtrace) to make functions and subshells inherit the ERR trap, which they do not by default.


Real World Example: A Preflight Runner That Reports Honestly

A preflight runner has the depot's exact job: run a list of checks, keep every code, and produce one verdict that does not lose the detail. It must not abort on the first failure, must distinguish a check that answered "no" from a check that could not run, and must survive a check that is a pipeline.

#!/usr/bin/env bash
set -uo pipefail

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
mkdir -p "$work/locked"

names=() codes=()
ran=0 fail=0

record() {
  names+=("$1")
  codes+=("$2")
  ran=$((ran + 1))
  [ "$2" -eq 0 ] || fail=$((fail + 1))
}

run_check() {
  local name=$1 status=0
  shift
  "$@" >/dev/null 2>&1 || status=$?
  record "$name" "$status"
}

verdict() {
  case $1 in
    0)   printf 'pass' ;;
    126) printf 'could not execute' ;;
    127) printf 'tool not found' ;;
    *)   printf 'failed' ;;
  esac
}

run_check config      true
run_check disk-space  bash -c 'exit 0'
run_check schema      bash -c 'exit 3'
run_check tls-cert    no-such-tool-here
run_check permissions "$work/locked"

status=0
bash -c 'printf "scanned 40 lines\n"; exit 6' | grep -q scanned || status=$?
record log-scan "$status"

printf '%-12s %5s  %s\n' CHECK CODE VERDICT
for i in "${!names[@]}"; do
  printf '%-12s %5d  %s\n' "${names[i]}" "${codes[i]}" "$(verdict "${codes[i]}")"
done
printf '%d checks ran, %d reported a problem\n' "$ran" "$fail"
[ "$fail" -eq 0 ] || exit 1

Output:

CHECK         CODE  VERDICT
config           0  pass
disk-space       0  pass
schema           3  failed
tls-cert       127  tool not found
permissions    126  could not execute
log-scan         6  failed
6 checks ran, 4 reported a problem
script exit 1

The last line is the caller reporting the runner's status. Six rows, six checks, and the counts reconcile: four of the six codes are non-zero and the summary says 4. The two zeros are config and disk-space; schema returned its own 3; tls-cert was a name the shell could not find, so the 127 came from bash rather than from any check; permissions pointed at a directory, which is the 126 case; and log-scan reported 6 even though grep succeeded.

That last row is pipefail earning its place. grep -q scanned found the line and exited 0, so without pipefail the pipeline's status would have been 0 and the check would have passed while its producer was failing. The idiom || status=$? is what makes the whole thing work under set -u: it captures the code instead of letting it propagate, so the loop continues and every check gets to run. Note that status=0 is reset before each use, because a leftover value from a previous check would be recorded against the next one.

run_check takes the check as "$@" rather than as a string to be re-parsed, which means a check whose arguments contain spaces still works and nothing is ever passed through eval. record is the only place that touches the arrays and the counters, so the invariant "one name, one code, one increment" holds by construction rather than by discipline. The final [ "$fail" -eq 0 ] || exit 1 is deliberate: without it the script's status would be the status of the last printf, which is the "round complete" scan that hides everything.

Now the limits, and the first one is a genuine design flaw. run_check runs every check as "$@" >/dev/null 2>&1, discarding both streams, so a failing check reports a number and nothing else. The operator is told that schema returned 3 and must now re-run it by hand to find out what it objected to -- the runner has thrown away the one thing that would make its own report actionable. Second, and worse for anyone consuming the result, record increments fail for any non-zero code, so tls-cert and permissions are counted as problems alongside schema. The VERDICT column knows those two never ran; the number 4 does not. A typo in a tool name is therefore indistinguishable from a real failure in the only figure a caller is likely to read. Third, the checks run in a fixed order with no dependencies, so schema still runs after config has failed, testing a schema against a configuration that could not be read and producing a code whose meaning is anybody's guess. Fourth, the runner exits 1 for any number of problems, so it cannot say "one cosmetic check failed" rather than "everything failed".


Common Mistakes

  1. Reading $? one command too late. $? is the status of the last command, not the last failure. A printf, a [ test, or an echo between the command and the check resets it to that command's status. Capture it on the very next line: cmd; status=$?.
  1. Writing a && b || c as an if-then-else. It parses as (a && b) || c, so c also runs when a succeeded and b failed, and the chain's status becomes c's. Use if a && b; then ...; else ...; fi whenever the branches are real alternatives.
  1. Trusting set -e to catch everything. It ignores failures in an if or while condition, on the left of && or ||, under !, and in every pipeline stage but the last. Four of the five failures in the demo above were ignored by design.
  1. Ending a script with a friendly message. With no explicit exit, a script's status is its last command's, and printf 'all done\n' succeeds. Finish with an explicit exit "$status" when the status matters.
  1. Treating 127 as a failing test. 127 means the shell never found the command and 126 means it could not execute it, so neither is an answer from your check. A runner that lumps them in with real failures cannot tell a typo from a genuine problem.
  1. Exiting with a count. exit "$errors" looks tidy until there are 256 errors, which arrives as 0. Statuses are one byte: use a small fixed set of codes and report counts on stdout.
  1. Losing PIPESTATUS before reading it. It is rebuilt by every command, including the printf you were about to use it in. Copy it first: stages=("${PIPESTATUS[@]}").
  1. Using || true to silence a command you still care about. It converts every failure, including ones you did not anticipate, into success. Prefer || status=$? and then decide, so the code is captured rather than discarded.
  1. Expecting a function's ERR trap to fire without set -E. Functions, subshells and command substitutions do not inherit an ERR trap by default, so a trap installed at the top of a script is silent inside the function where the failure actually happened.

Best Practices

  • Capture the status into a named variable immediately. cmd; status=$? on adjacent lines removes every question about what $? refers to later, and makes the intent readable to whoever adds a line in between.
  • Prefer if cmd; then over cmd; if [ "$?" -eq 0 ]. The first form cannot go stale when a line is inserted, reads as one thought, and does not need the status written down at all.
  • Use set -uo pipefail plus explicit checks rather than relying on set -e. -u and -o pipefail have no surprising exception list. Where you want an abort, write || exit 1 at the point it matters so the reader can see it.
  • Reserve 0, 1 and a couple of small numbers, and document them. A tool whose statuses mean something -- 0 pass, 1 check failed, 2 could not run -- lets a caller branch without parsing text. Stay away from 126, 127 and anything above 128.
  • Treat 126 and 127 as a separate class from a check's own failure. Report "tool not found" distinctly, because the remedy is completely different and no amount of re-running the check will help.
  • Copy PIPESTATUS on the line after the pipeline. stages=("${PIPESTATUS[@]}") preserves every stage; anything else you run first destroys it.
  • Give every non-trivial script an EXIT trap for cleanup, and keep it status-neutral. End the trap on a command that succeeds, or on nothing at all, so the pending status survives; never end it with exit 0.
  • Let functions return a status rather than exit. exit inside a function kills the whole script, which makes the function unusable from a chain or an if. Return the number and let the caller decide.

Practice Exercises

  1. Map the conventional statuses yourself. Write a script that provokes 0, 1, 2, 126, 127 and a signal death, printing $? after each, and put the six numbers in a table with a one-line explanation of who produced each. Predict them before running, and note which came from the shell rather than from a program.
  1. Prove the a && b || c trap. Write three functions that print their name and return a status you choose. Run a && b || c for all four combinations of a and b succeeding or failing, printing the chain's status each time. Then rewrite the intended logic with if and show that one of the four cases now behaves differently.
  1. Build a status-preserving wrapper. Write a function attempt that takes a name and a command, runs it, captures the status with || status=$?, prints a one-line verdict distinguishing 0 from 126 and 127 from any other non-zero, and returns the original status unchanged. Verify with a command that exits 3 that the caller still sees 3.
  1. Fix the preflight runner's counting flaw. Take the runner from the Real World Example and split its single fail counter into failed and unrunnable, counting 126 and 127 in the second. Exit 0 when both are zero, 1 when only failed is non-zero, and 2 when anything was unrunnable. Then address the first flaw by capturing each check's output to a per-check file and printing the last line of it beside any non-zero verdict.