Using set -u and set -o pipefail
Two shell options close gaps that ordinary Bash leaves open. set -u turns the use of an undefined variable into an error instead of silently replacing it with an empty string. set -o pipefail makes a pipeline report failure when any of its commands fails, instead of reporting only the status of the last command. Both options make mistakes visible that would otherwise pass unnoticed, and both are commonly combined with set -e (lesson 119), which lesson 121 covers.
set -u: Treat Unset Variables as Errors
The Problem
Bash expands a variable that was never assigned to an empty string, without any warning:
name=world
echo "hello $nmae"
echo "continues without -u"
hello
continues without -u
The typo nmae produced an empty value, and the script carried on. In a message this is only cosmetic, but the same mistake in a path can be destructive. If $build_dir is misspelled in rm -rf "$biuld_dir"/*, the command becomes rm -rf /* (lesson 160).
The Option
set -u # short form
set -o nounset # long form, same effect
With the option on, expanding an unset variable prints an error and, in a script, ends it:
set -u
name=world
echo "hello $nmae"
echo "not reached"
bash: nmae: unbound variable
The script's exit code was 1 in the test. "Unbound" is Bash's word for a variable that has no value at all. Note that the failed command (echo) never ran: the error happens while Bash is expanding the line, before the command starts.
In an interactive shell, the error is printed but the shell stays open, so set -u cannot close your terminal.
Unset Is Not the Same as Empty
set -u complains only about variables that do not exist. A variable set to an empty string is fine:
set -u
empty=
echo "empty is [$empty]"
empty is []
This mirrors the distinction lesson 45 drew between ${var-default} (used only when unset) and ${var:-default} (used when unset or empty).
What Counts as an Unset Variable
The check applies to every kind of parameter expansion. In the test, each of these ended the script with unbound variable:
| Expression | Why it fails |
|---|---|
$1 when no argument was given | Positional parameters beyond $# are unset |
$1 inside a function called without arguments | Functions have their own positional parameters (lesson 89) |
${#missing} | Taking the length still expands the variable |
${arr[5]} when index 5 does not exist | A missing array element is unset |
${map[key]} in an associative array without that key | Same rule for associative arrays |
$((y + 1)) with y unset | Arithmetic on an unset name |
$1 without arguments is the case that surprises most often:
set -u
echo "first arg: $1"
bash: $1: unbound variable
Some expansions are exempt by design, because "nothing" is a valid value for them. $#, "$@" and "$*" work with no arguments, and in Bash 5.2 so does "${arr[@]}" for an empty array:
set -u
echo "count: $#"
for a in "$@"; do echo "$a"; done
arr=()
for x in "${arr[@]}"; do echo "$x"; done
echo "empty array ok"
count: 0
empty array ok
Lesson 100 noted that Bash versions before 4.4 reported an error for an empty array expanded like this.
Providing Defaults
When a variable may legitimately be unset, give it a default with parameter expansion (lesson 45). The expansion is then never "unbound":
set -u
echo "first arg: ${1:-none}"
echo "${missing:-default}"
echo "${missing-}x"
first arg: none
default
x
${missing-} (or ${missing:-}) with nothing after the dash means "empty if unset". It is the standard way to test an optional variable under set -u:
set -u
if [ -z "${CONFIG:-}" ]; then
echo "CONFIG empty or unset"
fi
Without the :-, the test [ -z "$CONFIG" ] would itself fail with unbound variable.
To check whether a variable exists at all, Bash's -v test (lesson 69) does not expand the variable and is safe:
set -u
if [[ -v CONFIG ]]; then echo "set"; else echo "CONFIG not set"; fi
CONFIG not set
For a variable that must be provided, ${name:?message} stops the script with your own message (lesson 45):
set -u
: "${API_KEY:?API_KEY must be set}"
bash: API_KEY: API_KEY must be set
The : command does nothing; it exists so that the expansion is evaluated.
Things set -u Does Not Change
- Appending with
+=to an unset variable is allowed:unset x; x+=abcgivesabc. - Assigning is always allowed; only reading an unset variable is an error.
- The error cannot be handled with
||. In the test,echo "$UNDEF" || echo "handled"still ended the script, because the error happens during expansion, not as a command status. - Inside
$( ), the error ends only the subshell. The assignmentx=$(echo "$undef")printed the error and returned 1, and the script continued unlessset -ewas also active.
Portability
set -u is part of POSIX and works in Dash, which words the error differently:
dash -c 'set -u; echo "$zz"; echo after'
echo "status $?"
dash: 1: zz: parameter not set
status 2
set -o pipefail: Report Failures Inside Pipelines
The Problem
A pipeline's exit code is normally the exit code of its last command (lesson 61). A failure earlier in the pipeline disappears:
grep ERROR nofile.log | sort
echo "status without pipefail: $?"
grep: nofile.log: No such file or directory
status without pipefail: 0
grep failed with status 2, but sort successfully sorted its empty input, so the pipeline reports 0. set -e does not help, because it looks at the same pipeline status:
set -e
grep ERROR nofile.log | sort
echo "reached with only -e"
grep: nofile.log: No such file or directory
reached with only -e
The Option
set -o pipefail
There is no single-letter form. With pipefail on, a pipeline's status is the status of the last (rightmost) command that failed, or 0 if every command succeeded:
set -o pipefail
grep ERROR nofile.log | sort
echo "status with pipefail: $?"
grep: nofile.log: No such file or directory
status with pipefail: 2
The rule in more cases:
set -o pipefail
false | true | true; echo "false | true | true: $?"
true | false | true; echo "true | false | true: $?"
(exit 3) | (exit 5) | true; echo "3 | 5 | 0: $?"
true | true; echo "all ok: $?"
false | true | true: 1
true | false | true: 1
3 | 5 | 0: 5
all ok: 0
When several commands fail, the rightmost failure wins (5, not 3). PIPESTATUS still holds every individual status when you need them all (lesson 117).
Combined with set -e, a failure anywhere in a pipeline now stops the script:
set -eo pipefail
grep ERROR nofile.log | sort
echo "not reached"
The script ends with status 2, the status of grep.
The option also applies inside functions and command substitutions, because they inherit the shell's options:
set -o pipefail
f() { false | true; }
f
echo "function status: $?"
function status: 1
Caveat: "No Match" Becomes a Failure
grep returns 1 when it finds nothing. Under pipefail, a pipeline that searches and then counts reports failure whenever the count is zero:
set -o pipefail
printf 'INFO ok\n' > app2.log
grep ERROR app2.log | wc -l
echo "status: $?"
0
status: 1
wc printed the right answer, 0, but the pipeline's status is 1. With set -e also on, this line would end the script. Two ways around it:
set -eo pipefail
count=$(grep -c ERROR app2.log || true)
echo "count=$count"
count=0
grep -c counts by itself, so there is no pipeline, and || true accepts the "no match" status. When the pipeline is needed, put || true around the command whose status is an answer rather than an error:
count=$( { grep ERROR app2.log || true; } | wc -l )
As lesson 119 noted, || true also hides real errors such as a missing file. Where that matters, save the status and examine it, as in the complete example at the end of this lesson.
Caveat: SIGPIPE When the Reader Stops Early
Commands such as head stop reading once they have what they need. The command writing into the pipe is then killed by SIGPIPE the next time it writes, and its status is 141 (128 + 13, lesson 116). Without pipefail, that status is invisible. With it, the pipeline fails:
set -o pipefail
seq 1 100000 | head -n 1
echo "status: $? (${PIPESTATUS[*]})"
1
status: 141 (141 0)
The output is correct, yet the status says "failed". With set -e as well, a script stops silently at such a line. In the test, this script ended with status 141 on every run and printed nothing:
set -eo pipefail
first=$(seq 1 100000 | head -n 1)
echo "first=$first"
Whether SIGPIPE happens depends on timing and on how much data the writer still has to send. printf 'a\nb\n' | head -n 1 returned 0 in the test, because printf had written everything before head exited. A pipeline that works in testing with small files can therefore fail later with large ones.
Solutions:
- Let the writer finish: replace
head -n 1with a command that reads all input, such assed -n 1porawk 'NR == 1'.first=$(seq 1 100000 | sed -n 1p)returned 0 in the test. - Limit the output at the source when the command supports it:
grep -m 1stops after the first match instead of piping intohead -n 1. - Accept 141 explicitly for that one pipeline, for example by checking
PIPESTATUSinstead of relying onpipefail.
Portability
pipefail is available in Bash, Ksh and Zsh. It was added to the POSIX standard only recently, and many /bin/sh implementations do not support it yet. The Dash version installed on Ubuntu 24.04 (0.5.12) rejected it:
dash -c 'set -o pipefail; false | true; echo "$?"'
dash: 1: set: Illegal option -o pipefail
Scripts that use pipefail should start with a Bash shebang (lesson 26). Lesson 188 covers portable scripts.
Checking Which Options Are On
set -o without arguments lists every option with its state, and $SHELLOPTS holds the enabled ones separated by colons:
set -o pipefail
echo "$SHELLOPTS" | tr ':' '\n' | grep pipefail
set +o pipefail
set -o | grep pipefail
pipefail
pipefail off
set +u and set +o pipefail turn the options off again, for example around a short section of code that relies on the default behavior. Lesson 148 covers set in general.
A Complete Example
This script lists the most frequent ERROR lines in a log file. It uses set -u to catch variable mistakes and pipefail to notice when grep fails, and it examines the pipeline's status itself so that "no errors" and "cannot read the file" are handled differently:
#!/usr/bin/env bash
set -uo pipefail
log=${1:-}
if [ -z "$log" ]; then
echo "usage: ${0##*/} LOGFILE" >&2
exit 2
fi
top=$(grep -h ERROR -- "$log" | sort | uniq -c | sort -rn)
rc=$?
case $rc in
0) echo "most frequent errors:"; echo "$top" ;;
1) echo "no errors in $log" ;;
*) echo "${0##*/}: cannot read $log" >&2; exit 1 ;;
esac
printf 'ERROR disk full\nINFO ok\nERROR timeout\nERROR disk full\n' > app3.log
printf 'INFO ok\n' > clean.log
./toperr.sh; echo "status $?"
./toperr.sh app3.log; echo "status $?"
./toperr.sh clean.log; echo "status $?"
./toperr.sh missing.log; echo "status $?"
usage: toperr.sh LOGFILE
status 2
most frequent errors:
2 ERROR disk full
1 ERROR timeout
status 0
no errors in clean.log
status 0
grep: missing.log: No such file or directory
toperr.sh: cannot read missing.log
status 1
How it works:
${1:-}reads the first argument without triggeringset -uwhen it is missing, and the empty check prints a usage message instead of$1: unbound variable.- Because of
pipefail,rccarries the status ofgrep(1 for no match, 2 for an unreadable file) even thoughgrepis the first of four commands. The other commands succeed, sogrep's status is the rightmost failure. - The assignment
top=$(...)keeps the pipeline's status in$?(lesson 117), andrc=$?saves it on the next line. set -eis not used here, because status 1 fromgrepis a normal answer that the script wants to handle itself.
With pipefail removed, the last case printed most frequent errors: followed by an empty line and exited with 0, the misleading result this option exists to prevent.
The examples were run with Bash 5.2.21, Dash 0.5.12, GNU grep 3.11 and GNU coreutils 9.4. Error messages are shown in their interactive form; in a script, Bash adds the script name and line number in front.