Using set -u and set -o pipefail

Su Suriya Ravichandran Updated 06 Dec 2026
11 min read ·Lesson 120 of 205

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:

ExpressionWhy it fails
$1 when no argument was givenPositional parameters beyond $# are unset
$1 inside a function called without argumentsFunctions have their own positional parameters (lesson 89)
${#missing}Taking the length still expands the variable
${arr[5]} when index 5 does not existA missing array element is unset
${map[key]} in an associative array without that keySame rule for associative arrays
$((y + 1)) with y unsetArithmetic 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+=abc gives abc.
  • 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 assignment x=$(echo "$undef") printed the error and returned 1, and the script continued unless set -e was 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 1 with a command that reads all input, such as sed -n 1p or awk '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 1 stops after the first match instead of piping into head -n 1.
  • Accept 141 explicitly for that one pipeline, for example by checking PIPESTATUS instead of relying on pipefail.

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 triggering set -u when it is missing, and the empty check prints a usage message instead of $1: unbound variable.
  • Because of pipefail, rc carries the status of grep (1 for no match, 2 for an unreadable file) even though grep is the first of four commands. The other commands succeed, so grep's status is the rightmost failure.
  • The assignment top=$(...) keeps the pipeline's status in $? (lesson 117), and rc=$? saves it on the next line.
  • set -e is not used here, because status 1 from grep is 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Using set -u and set -o pipefail and get answers drawn from it.

Signed-in readers only.