Robust Error Handling

Robust Error Handling in Bash: --- On a modern assembly line there is a cord -- or a button -- strung along the whole length of the floor, within reach of…


The Analogy: The Andon Cord Above an Assembly Line

On a modern assembly line there is a cord -- or a button -- strung along the whole length of the floor, within reach of every operator. It is called the andon cord. The rule is simple and famous: the moment anyone sees a defect they cannot immediately fix, they pull the cord. A light flashes, a tune plays, and that section of line stops. The defect does not travel to the next station. Work halts while the fault is understood, because the cost of stopping for a minute is trivial next to the cost of building a hundred more units on top of a broken one.

The andon cord encodes a decision about when to fail. A line without one keeps moving no matter what: a missing bolt at station three becomes a trapped wiring loom at station nine, and by the time anyone notices, every unit carries the same flaw and the rework is enormous. The cord inverts that. It makes the first fault the cheapest possible fault, because it is caught at the station that created it, with the context still fresh and only one unit affected.

A shell script is an assembly line for commands. Each command hands its work to the next, and an early failure that is ignored does not stay contained -- it corrupts everything downstream. Robust error handling is the andon cord: a small set of switches -- set -e, set -u, set -o pipefail -- plus a habit of turning silent checks into loud decisions, so the first command to fail stops the whole run instead of feeding a broken result into the next step. The default shell has no cord; a command that fails simply sets a status nobody reads, and the script marches on.

The failure mode is the cord that has been tied off. On real factory floors, under pressure to hit a quota, the andon system is sometimes disabled -- the button unwired, the cord looped out of reach -- because stopping the line "costs too much." Defects then flow through untouched and surface as a whole shift of scrap at final inspection, far from where they began and far more expensive to trace. Scripts are tied off the same way: set -e left out, failures papered over with || true, errors flushed to /dev/null. The line keeps moving, and the damage is discovered only when the deploy is already half done.


Syntax or Core Structure

The three switches are almost always used together, written as one line near the top of a script:

set -euo pipefail

Each letter wires a different part of the cord. set -e stops the script the moment a command fails; set -u treats the use of an unset variable as a failure; set -o pipefail makes a pipeline fail if any stage fails, not just the last. Taken apart, set -e alone already changes the default "keep going" behaviour:

set -e
echo one
false
echo two

Output:

one

echo one succeeds and prints. false does nothing but return status 1; with set -e that non-zero status stops the script immediately, so echo two never runs and the script exits 1. Without set -e all three lines would run and the failure of false would pass unnoticed.

set -u guards against the other silent error, the variable you only thought you set:

set -u
name="Ada"
echo "$name"
echo "$missing"

Output:

Ada

name prints normally. Referencing missing, which was never assigned, makes bash print missing: unbound variable to standard error and exit non-zero, so nothing after it runs. In the default shell $missing would silently expand to the empty string -- exactly the kind of blank that turns rm -rf "$prefix"/ into a command that starts deleting at the root.

set -o pipefail closes the last gap, the pipeline:

false | cat
echo "no-pipefail rc=$?"
set -o pipefail
false | cat
echo "pipefail rc=$?"

Output:

no-pipefail rc=0
pipefail rc=1

A pipeline normally reports only the status of its last command, so false | cat looks successful because cat succeeded. With pipefail the pipeline's status becomes the rightmost non-zero one, so the failure of false is visible and, under set -e, would stop the script.


Technical Depth: Where the Cord Is Wired, and Where It Is Not

The three switches at a glance

SwitchFires whenConsequence without it
set -eany untested command returns non-zerothe script continues past failures
set -uan unset variable is expandedunset silently becomes an empty string
set -o pipefailany stage of a pipeline failsonly the final stage's status counts
set -Ean ERR trap should run inside functionsthe trap is skipped in functions

The first three are the everyday triad. The fourth, set -E with a capital E, matters only once you add an ERR trap and want it to fire inside functions and subshells too; it is covered with traps in the next topic. Written together the incantation is set -euo pipefail, and it belongs on its own line before the first real command.

The blind spots of set -e

set -e is not a promise that any failure anywhere stops the script. By design it looks away in several places, and knowing them is the difference between a cord you trust and one you only think is wired:

set -e
if false; then echo hi; fi
echo "survived the if"
false || echo "handled"
echo "survived the ||"
echo done

Output:

survived the if
handled
survived the ||
done

None of those failures stopped the script. A command used as an if condition is expected to be able to fail, so set -e ignores its status. The same applies to any command on the left of && or ||, and to every command in a pipeline except the last unless pipefail is set. These are not bugs; they are the rule. The practical consequence is that set -e handles the failures you did not anticipate, while the ones you do anticipate still need an explicit decision.

Turning a check into a decision

Where set -e looks away, you make the choice yourself. Two patterns cover almost everything. The ${var:?message} form asserts a variable is set and aborts with your message if it is not:

: "${CONFIG:?CONFIG is required}"
echo "using $CONFIG"

If CONFIG is unset the shell prints CONFIG: CONFIG is required to standard error and exits without ever reaching the echo. The || { ...; exit 1; } form turns any failing command into a guarded exit with a readable message:

command -v jq >/dev/null 2>&1 || { echo "missing required tool: jq" >&2; exit 1; }

Output:

missing required tool: jq

With jq absent the check is explicit, the message names the problem, and the deliberate non-zero exit pulls the andon cord on purpose rather than by accident. A guard clause like this at the top of a script is worth more than any amount of cleanup at the bottom.

Capturing a status without tripping the cord

Sometimes you need a command's exit status without letting set -e stop the script -- you want to branch on the result, not abort on it. Two idioms do this cleanly. Putting the command in an if lets you handle both outcomes in place:

set -e
if grep -q needle file.txt; then
  echo "found"
else
  echo "not found (rc was non-zero, script continues)"
fi
echo done

Output:

not found (rc was non-zero, script continues)
done

The failing grep is a condition, so set -e ignores its status and the else branch runs. When you want the number itself, capture it on the same line with || rc=$?, which also sits on the left of || and is therefore exempt:

set -e
rc=0
grep -q needle file.txt || rc=$?
echo "miss rc=$rc"
rc=0
grep -q alpha file.txt || rc=$?
echo "hit rc=$rc"

Output:

miss rc=1
hit rc=0

Both idioms keep the script running while still telling you exactly what happened. They exploit the same rule that makes set -e blind to if conditions and || left-hands: a status you explicitly inspect is a status you have chosen to handle, so the cord stays up. The distinction is worth internalising: set -e is for the failures you have not thought about, and these capture idioms are for the ones you have. A script that mixes the two deliberately -- strict by default, explicit exactly where a decision is needed -- is far easier to trust than one that either aborts unpredictably or swallows every error in sight.


Real World Example: A Deploy Preflight That Refuses to Start

Most deploy disasters are not exotic: a missing environment variable, a tool that is not installed on this runner, or an artifact that was never built. A preflight script does nothing but check those preconditions and refuse to continue if any is wrong -- the andon cord pulled before the line even starts moving. preflight.sh requires an environment name, requires the tools it will use, and requires the artifact file to exist:

#!/usr/bin/env bash
# preflight.sh -- verify the environment before a deploy, or refuse to start
set -euo pipefail

: "${DEPLOY_ENV:?set DEPLOY_ENV (staging|production)}"

require() {
  command -v "$1" >/dev/null 2>&1 || { echo "missing required tool: $1" >&2; exit 1; }
}

require tar
require gzip

artifact="${1:?usage: preflight.sh ARTIFACT}"
if [ ! -f "$artifact" ]; then
  echo "artifact not found: $artifact" >&2
  exit 1
fi

echo "env: $DEPLOY_ENV"
echo "artifact: $artifact"
echo "preflight passed"
DEPLOY_ENV=staging bash preflight.sh app.tar.gz

Output:

env: staging
artifact: app.tar.gz
preflight passed

On the happy path the script is quiet and linear: the ${DEPLOY_ENV:?} assertion passes because the variable is set, the two require calls find tar and gzip, the positional argument supplies the artifact name, and the file exists, so the three status lines print and the script exits 0. Nothing here is defensive noise -- every line is a precondition that, if unmet, would have made the real deploy fail later and far more mysteriously.

DEPLOY_ENV=staging bash preflight.sh nope.tar.gz

Output:

artifact not found: nope.tar.gz

Point it at a file that does not exist and the cord is pulled at the last check: the message names the exact missing artifact, the script exits 1, and the deploy never begins. Remove DEPLOY_ENV from the environment and it stops even earlier, at the very first line, with set DEPLOY_ENV (staging|production) on standard error. Each failure is loud, specific, and positioned as early as the missing information allows.

The script is honest about presence but naive about correctness. require tar confirms some tar exists on the PATH; it does not confirm it is GNU tar, a compatible version, or not a same-named script shadowing the real one. The [ ! -f "$artifact" ] test confirms the file exists but not that it is a valid, non-empty, uncorrupted archive -- an empty file passes it. And the whole design leans on set -euo pipefail sitting at the top: delete that one line and every unchecked command silently reverts to "keep going," so the preflight becomes merely advisory. Those switches are load-bearing, which is exactly why they belong on their own conspicuous line rather than buried in the middle of the script.


Common Mistakes

  1. Assuming set -e catches every failure. It ignores commands used as if/while conditions, on the left of &&/||, and inside pipelines without pipefail. Anticipated failures still need explicit handling.
  1. Omitting pipefail. In curl url | tar xz only tar's status is reported, so a failed download that yields an empty stream looks like a success.
  1. Leaving expansions unquoted under set -u. set -u catches unset names but not word-splitting or globbing; $file and "$file" diverge the moment the value contains a space.
  1. Papering over failures with || true. It silences the cord for that command permanently. Use it only where a non-zero status is genuinely expected and harmless.
  1. Redirecting all errors to /dev/null. 2>/dev/null on a whole command hides the very message you will need when it fails; redirect only the specific noisy stream.
  1. Reading $? several commands later. $? reflects only the most recent command, so capture it into a variable on the same line or test it immediately.
  1. Putting set -euo pipefail after the first real work. Everything above that line runs under the lenient defaults; the switches must precede the first command that matters.
  1. Expecting set -e to work inside a function called as f && g. A function invoked on the left of && or || runs with set -e suspended, so failures inside it do not stop the script.
  1. Treating an empty variable as safe. With the default shell an unset prefix turns rm -rf "$prefix"/data into rm -rf /data; set -u together with ${prefix:?} is what prevents it.

Best Practices

  • Open scripts with set -euo pipefail. Put it on its own line before the first command so the whole run happens with the cord wired.
  • Assert required inputs with ${var:?message}. Fail at the top with a message that names what is missing, not deep inside where the symptom is confusing.
  • Guard external tools with a require helper. Check command -v tool once, up front, so a missing dependency stops the run before it does partial work.
  • Decide anticipated failures explicitly. Reserve set -e for the failures you did not foresee, and handle the ones you expected with || { ...; exit 1; }.
  • Read a command's status immediately. Test it on the next line or use || on the command itself; never assume $? survives intervening commands.
  • Send diagnostics to standard error. Use >&2 for messages so they stay visible even when standard output is captured or piped.
  • Quote every expansion. "$var" and "${array[@]}" keep set -u meaningful and stop values that contain spaces from splitting.
  • Keep the switches conspicuous. Do not bury or conditionally set set -e; a reader must see at a glance that the cord is wired.

Practice Exercises

  1. Prove the blind spots. Write a script with set -e that shows a failing command surviving as an if condition, on the left of ||, and mid-pipeline, then add pipefail and show the pipeline case now stops the script.
  1. Write a require helper. Implement a function that aborts with missing required tool: NAME on standard error and exit 1 when a named command is absent, then call it for two tools, one present and one not.
  1. Guard a destructive command. Take rm -rf "$TARGET"/cache and make it safe: assert TARGET is set with ${TARGET:?}, refuse to run if it is empty or /, and print what it would delete before deleting it.
  1. Convert lenient to strict. Given a script with no set switches that silently continues past a failed mkdir, add set -euo pipefail, fix the two failures it now surfaces, and explain in a comment why each was previously invisible.