set -euo pipefail Explained: What Each Flag Actually Protects You From

Almost every serious bash script starts with set -euo pipefail. Almost nobody who pastes it can tell you what it guarantees, and — more dangerously — where it quietly does not.

This is the header that turns bash from a language that ignores errors by default into one that stops at the first sign of trouble. It is worth understanding properly, because it is doing a lot of work in your deploy scripts, your CI jobs and your cron entries, and because its protection has holes that a wrong assumption will drive a production incident straight through. Here is each flag, what it actually protects you from, and the three cases where -e looks like it is guarding you and is not. Behaviour described here is for bash 5.2 with GNU coreutils.

The header, annotated

The canonical strict-mode header is four lines, not one. The IFS reset is not part of set at all, but it belongs with it.

Free · 4 minutes

Is your engineering team shipping safely, or quietly accumulating risk?

Fourteen questions on how work gets from idea to production — cadence, testing, rollback, and the key-person risk in your delivery. Banded finding on screen, full sheet by email.

#!/usr/bin/env bash
set -euo pipefail
IFS=$'nt'

# -e (errexit)  : exit immediately if any command exits non-zero
# -u (nounset)  : treat use of an unset variable as an error and exit
# -o pipefail   : a pipeline fails if ANY command in it fails, not just the last
# IFS=$'nt'   : split words on newline and tab only, never on spaces

Read as a sentence: stop on the first error, refuse to read a variable I never set, do not let a failure in the middle of a pipeline be swallowed, and do not silently split my filenames on spaces. Each clause defends against a specific, common way shell scripts go wrong. Take them in turn.

-e (errexit): stop before the damage compounds

Without -e, bash runs the next command regardless of whether the last one worked. The textbook disaster is the two-liner cd "$build_dir"; rm -rf ./*. If the cd fails because the directory is missing, the script marches on and deletes everything in whatever directory it happened to be in. set -e aborts at the failed cd and the rm never runs. That single behaviour — do not proceed after a step that did not succeed — is what most people are actually buying.

What -e protects against is the compounding failure: the step that assumes the previous step worked, operating on state that was never created. It is the difference between a script that fails loudly at line 12 and one that runs to completion having done half its job in the wrong place.

The three cases where -e does not fire

This is the part that costs people. errexit has exceptions written into the POSIX shell specification, and each one is a place where a command can fail while the script sails on. If you believe -e is absolute, these will surprise you at the worst time.

# 1. Anything tested in a condition, or joined with && or ||, is exempt.
#    errexit is suppressed for the whole thing being tested — including
#    the entire body of a function called this way.
check_input() {
    grep -q "pattern" missing_file   # fails...
    echo "but this still runs"        # ...and so does this
}
if check_input; then echo "ok"; fi    # the internal failure is swallowed

# 2. A command substitution assigned via local/declare/export/readonly.
#    The declaration builtin returns 0, masking the real exit status.
read_config() {
    local value=$(grep missing /etc/app.conf)   # grep fails; script continues
    local value                                   # declare separately, THEN
    value=$(grep missing /etc/app.conf)           # assign: now -e fires
}

# 3. Any command in a pipeline except the last (without pipefail).
grep "pattern" missing_file | sort    # grep fails, sort succeeds
                                       # pipeline "succeeds", -e stays quiet

The first case is the nastiest, because it is invisible: putting a function on the left of && or inside an if turns off errexit for every line inside that function, not just the tested command. Code that is safe when called normally becomes unsafe when called in a condition. The second is the reason experienced authors declare and assign on separate lines. The third is precisely what pipefail exists to close.

There is a mirror-image trap worth knowing: -e can fire when you do not expect it. ((count++)) evaluates to the value of count before the increment, so when count is 0 the arithmetic returns a non-zero exit status and the script exits. Use count=$((count + 1)) instead.

-u (nounset): fail on the variable you forgot to set

Without -u, a reference to an unset variable expands to an empty string. That turns a typo in a variable name into a silent bug, and it turns rm -rf "$PREFIX/data" — where PREFIX was never exported — into rm -rf /data. set -u makes that expansion an error and stops the script cold.

The cost is that genuinely optional variables now need explicit handling. Bash gives you the syntax for it: ${VAR:-default} supplies a fallback, and ${VAR:-} says “empty is fine here, on purpose”. Reach for those rather than switching -u off. In bash 5.2, "$@" with no positional parameters no longer trips nounset — that footgun existed before 4.4, but you will not meet it on a current shell.

-o pipefail: the failure in the middle of a pipe

By default a pipeline reports only the exit status of its last command. So curl -f https://api.example.com/data | jq '.items' returns success as long as jq parses whatever it received — even if curl failed and passed it nothing. With pipefail, the pipeline takes the status of the rightmost command that exited non-zero, so the failed curl now fails the pipeline, and combined with -e the script stops. This is the flag that makes the other two trustworthy inside pipelines, which is where a lot of real shell work happens.

One honest caveat: pipefail can produce failures you did not intend when a downstream command legitimately closes the pipe early. producer | head -n 1 leaves producer to receive SIGPIPE (exit 141) when head stops reading, and pipefail dutifully reports the pipeline as failed. Know that pattern so you can special-case it rather than being baffled by it.

IFS: the space in the filename

The default Internal Field Separator is space, tab and newline, which means unquoted expansions split on spaces. A file named quarterly report.csv becomes two arguments, quarterly and report.csv, and loops over filenames break the moment someone uses a space. Setting IFS=$'nt' removes the space from the split set, so word splitting happens only on newlines and tabs. It is a smaller protection than the others and it is not a substitute for quoting your expansions — "$var", always — but it turns a class of whitespace bugs from silent misbehaviour into something that mostly just works.

What the header actually guarantees

set -euo pipefail plus a sane IFS gives you a shell that stops at the first unhandled failure, refuses to read variables you never set, and catches failures anywhere in a pipeline. That is a large improvement over stock bash and it belongs at the top of every non-trivial script. What it does not give you is immunity. Functions called in conditions, command substitutions assigned through local, and arithmetic that returns zero all slip past errexit, and no amount of pasting the header changes that.

The practical move is to run ShellCheck as part of a pre-commit baseline that actually runs, because it flags most of these exceptions before they ship, and to treat your deploy scripts as production code that earns its place in the same delivery metrics as everything else you measure across the pipeline. Strict mode is a floor, not a ceiling. Paste the header, then write as though it might not save you — because in three specific, common cases, it will not.

Free interactive tool

Website compliance checklist

What your site has to do, based on what it actually does

Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.

Most technology problems are not technology problems. They are control problems.

The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.