Combining Strict Mode Options Safely

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 121 of 205

"Strict mode" is the informal name for turning on three shell options together at the top of a Bash script:

set -euo pipefail

Lesson 119 covered set -e (stop when a command fails), and lesson 120 covered set -u (treat unset variables as errors) and set -o pipefail (let a failure anywhere in a pipeline count). Each option closes a different gap, and together they turn many silent mistakes into immediate, visible failures. They also interact with each other and with the rest of the script in ways that are easy to get wrong. This lesson shows how to combine them, which extra settings complete the picture, and which coding patterns keep a strict script working as intended.

What Each Option Contributes

OptionLong formCatches
-eset -o errexitA command fails and the script carries on as if nothing happened
-uset -o nounsetA misspelled or never-assigned variable expands to an empty string
-o pipefailset -o pipefailA command early in a pipeline fails but the last command succeeds

No single option covers the others. set -e alone does not notice a failed grep in grep ERROR file | sort, because the pipeline's status is that of sort. pipefail alone changes the pipeline's status but does not stop the script. set -u is about variables, not command statuses at all. That is why they are normally used as a set.

Spelling the Line

These lines all have the same effect:

set -euo pipefail
set -e -u -o pipefail
set -o errexit -o nounset -o pipefail

Running each one and printing the enabled single-letter flags in $- and the long names in $SHELLOPTS gave the same result every time:

ehuBc
braceexpand:errexit:hashall:interactive-comments:nounset:pipefail

In set -euo pipefail, the letters e and u are separate flags, and o takes the next word, pipefail, as its argument. The long form is easier to read for someone who has not memorized the letters; the short form is what most scripts use.

Put It on Its Own Line, Not in the Shebang

It is tempting to move the options into the shebang line (lesson 26). On Linux this does not work, because the kernel passes everything after the interpreter path as a single argument:

#!/usr/bin/env bash -euo pipefail
echo hi
/usr/bin/env: 'bash -euo pipefail': No such file or directory
/usr/bin/env: use -[v]S to pass options in shebang lines

env looked for a program literally named bash -euo pipefail. With an absolute path the result is different but still broken:

#!/bin/bash -euo pipefail
/bin/bash: line 0: /bin/bash: ./sheb2.sh: invalid option name

Bash received -euo pipefail as one word and could not parse it. GNU env -S splits the line correctly (#!/usr/bin/env -S bash -euo pipefail worked in the test), but -S is not available everywhere, and every shebang option is ignored when someone runs the file as bash script.sh. In that test, the same file printed flags ehuB when executed directly and flags hB when run with bash. A set line inside the script applies no matter how the script is started, so that is the reliable place:

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

Completing the Picture: Two Gaps the Three Options Leave

Gap 1: Command Substitution Ignores set -e

Lesson 119 showed that $( ) runs in a subshell that does not inherit set -e. A function that fails partway through therefore keeps running inside a command substitution:

set -euo pipefail
f() { false; echo "f continued"; }
x=$(f)
echo "x=[$x] without inherit_errexit"
shopt -s inherit_errexit
y=$(f)
echo "not reached"
x=[f continued] without inherit_errexit

The script's exit status was 1. In the first call, false failed but f continued and its last command, echo, succeeded, so the assignment succeeded and the failure was lost. After shopt -s inherit_errexit (available since Bash 4.4), the subshell inherits -e, false ends the subshell with status 1, the assignment y=$(f) fails, and the main script stops.

Gap 2: The ERR Trap Does Not Reach Functions

An ERR trap runs a command whenever a command fails in a way that set -e would act on. It is a convenient place to print where a strict script stopped (lesson 123 covers traps in detail):

set -euo pipefail
trap 'echo "error: line $LINENO: $BASH_COMMAND (status $?)" >&2' ERR
echo start
ls /nonexistent
echo "not reached"
start
ls: cannot access '/nonexistent': No such file or directory
error: line 4: ls /nonexistent (status 2)

$LINENO is the line of the failing command, $BASH_COMMAND is the command text, and $? is its status. The script then ended with status 2.

The trap is not inherited by functions, though. This script failed inside a function and stopped with status 1 without printing anything:

set -euo pipefail
trap 'echo "error: line $LINENO: $BASH_COMMAND (status $?)" >&2' ERR
f() { false; echo "after false in f"; }
f

Adding -E (long form set -o errtrace) makes functions, command substitutions and subshells inherit the ERR trap. With set -Eeuo pipefail the same script printed:

error: line 3: false (status 1)

The Extended Header

A header that closes both gaps looks like this:

#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit
trap 'echo "${0##*/}: line $LINENO: \"$BASH_COMMAND\" failed with status $?" >&2' ERR

The three basic options do the real work. -E, inherit_errexit and the trap make the behavior more consistent and the failures easier to locate. inherit_errexit requires Bash 4.4 or later, which matters on older systems (macOS ships Bash 3.2 as /bin/bash, lesson 8).

What About IFS?

Some popular articles add IFS=$'\n\t' to the strict mode header. IFS controls word splitting (lesson 53). Setting it to newline and tab means unquoted expansions no longer split on spaces. In the test:

files="a b.txt c.txt"
for f in $files; do echo "default: [$f]"; done
IFS=$'\n\t'
for f in $files; do echo "newline-tab IFS: [$f]"; done
arr=(x y z)
echo "joined with \"\${arr[*]}\": ${arr[*]}"
read -r a b <<< "first second"
echo "read: a=[$a] b=[$b]"
default: [a]
default: [b.txt]
default: [c.txt]
newline-tab IFS: [a b.txt c.txt]
joined with "${arr[*]}": x
y
z
read: a=[first second] b=[]

The change protects unquoted variables that contain spaces, but it changes other behavior along the way: "${arr[*]}" now joins with a newline, and read no longer splits a line into words on spaces. This is not an error-handling setting, and it is not a substitute for quoting (lesson 55). If a script sets it, every read and every "$*" must be written with the new value in mind. The header in this tutorial leaves IFS alone and relies on quoting.

Patterns That Stay Safe Under Strict Mode

Strict mode stops the script on things that ordinary Bash code does all the time on purpose: a grep that finds nothing, an optional argument that was not given, a counter that starts at zero. Each of these has a standard form that expresses the intent clearly:

set -euo pipefail
printf 'INFO ok\n' > clean.log
count=$(grep -c ERROR clean.log || true)
echo "count=$count"
rc=0
grep -q ERROR clean.log || rc=$?
echo "grep rc=$rc"
i=0
(( ++i ))
echo "i=$i after ((++i))"
j=0
j=$((j + 1))
echo "j=$j"
echo "arg: ${1:-none}"
if [[ -n ${DEBUG-} ]]; then echo debug; else echo "DEBUG not set"; fi
k=0
(( k++ ))
echo "not reached"
count=0
grep rc=1
i=1 after ((++i))
j=1
arg: none
DEBUG not set

The script ended with status 1 at the last arithmetic command. Line by line:

SituationSafe formWhy it works
A count may be zeron=$(grep -c PAT file || true)grep -c prints 0 and returns 1; || true accepts that status
A status is an answer, not an errorrc=0; cmd || rc=$?A command on the left of || does not trigger set -e; rc keeps the real status
A test decides what to doif cmd; then ...Conditions of if, while and until are exempt from set -e
Incrementing a counter(( ++i )) or i=$((i + 1))(( i++ )) evaluates to the old value 0, which (( )) reports as status 1
Optional argument${1:-default} or ${1:-}A default makes the expansion never "unbound"
Optional environment variable${DEBUG-}Empty if unset, so set -u does not complain
Capturing output in a functionlocal out; out=$(cmd)local out=$(cmd) returns the status of local (0) and hides the failure

The last row deserves a test of its own:

set -euo pipefail
f() { local out=$(false); echo "hidden failure, out=[$out]"; }
g() { local out; out=$(false); echo "not reached"; }
f
g
echo "not reached either"
hidden failure, out=[]

The script then stopped with status 1 inside g. Splitting the declaration from the assignment lets the assignment carry the status of the command substitution.

One caution about || true: it accepts every non-zero status, including real errors such as a missing file (status 2 for grep). When the difference matters, save the status and examine it, as the rc=0; cmd || rc=$? row does and as lesson 122 shows with if and case.

Turning Strict Mode Off for a Few Lines

Sometimes a short block needs the default behavior, for example to run a command whose status you want to inspect directly. set +e turns the option off and set -e turns it back on:

set -euo pipefail
set +e
grep -q needle /nonexistent 2>/dev/null
rc=$?
set -e
echo "grep status was $rc, script continues"
false
echo "not reached"
grep status was 2, script continues

The final false stopped the script with status 1, showing that -e was active again.

Saving and Restoring Options Correctly

Code that does not know which options its caller has set, such as a function in a shared library, should save the current settings and restore them instead of assuming. set +o prints the current settings as commands that recreate them:

set -o errexit
set -o nounset
set -o pipefail

The obvious approach captures that output with $( ) and replays it with eval. It has a trap in it:

set -euo pipefail
saved=$(set +o)
set +eu +o pipefail
echo "inside: $-"
eval "$saved"
echo "restored: $- ; $(set -o | grep pipefail)"
inside: hB
restored: huB ; pipefail       	on

nounset and pipefail came back, but errexit did not: $- shows huB without e. The reason is Gap 1 again. set +o ran inside a command substitution, which does not inherit -e, so it reported set +o errexit. With inherit_errexit on, the subshell sees the real setting:

set -euo pipefail
echo "in \$( ): $(set +o | grep errexit)"
shopt -s inherit_errexit
echo "with inherit_errexit: $(set +o | grep errexit)"
in $( ): set +o errexit
with inherit_errexit: set -o errexit

After adding shopt -s inherit_errexit before the save, the restore printed restored: ehuB ; pipefail on. Another approach avoids the subshell altogether by checking $- for the e flag before changing it:

had_e=0
[[ $- == *e* ]] && had_e=1
set +e
some_command
rc=$?
(( had_e )) && set -e

Where Strict Mode Does Not Belong

Files Meant to Be Sourced

Options are properties of the shell, not of a file. A library loaded with source (lesson 95) that runs set -euo pipefail changes the caller's shell too:

# lib.sh
set -euo pipefail
greet() { echo "hello"; }
# caller.sh
source ./lib.sh
greet
echo "caller flags: $-"
echo "value: $undefined_var"
echo "not reached"
hello
caller flags: ehuB
caller.sh: line 4: undefined_var: unbound variable

caller.sh never asked for strict mode, but it stopped with status 1 on an unset variable. Libraries should leave option choices to the script that loads them; the main script decides.

Interactive Shells

Putting set -e into ~/.bashrc would make the interactive shell exit the first time any command fails, closing the terminal window. In the test, bash -i -c 'set -e; false; echo "after false"' ended with status 1 and never printed the message. Strict mode is for scripts. (set -u alone is less drastic in an interactive shell, as lesson 120 showed, but it still turns every typo in a variable name into an error message.)

A Complete Example

This script counts ERROR lines in every .log file of a directory. It uses the extended header, handles a missing argument and an empty directory as normal cases, and lets strict mode catch real failures:

#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit nullglob

trap 'echo "${0##*/}: line $LINENO: \"$BASH_COMMAND\" failed with status $?" >&2' ERR

dir=${1:-}
if [[ -z $dir ]]; then
    echo "usage: ${0##*/} DIRECTORY" >&2
    exit 2
fi

cd -- "$dir"

logs=(*.log)
if (( ${#logs[@]} == 0 )); then
    echo "no .log files in $dir"
    exit 0
fi

total=0
for f in "${logs[@]}"; do
    n=$(grep -c ERROR -- "$f" || true)
    printf '%-10s %s\n' "$f" "$n"
    total=$(( total + n ))
done
echo "total errors: $total"

With a logs folder holding app.log (two ERROR lines) and web.log (none), an empty folder logs2, and no folder named missing:

./errcount.sh;          echo "status $?"
./errcount.sh logs;     echo "status $?"
./errcount.sh logs2;    echo "status $?"
./errcount.sh missing;  echo "status $?"
usage: errcount.sh DIRECTORY
status 2
app.log    2
web.log    0
total errors: 2
status 0
no .log files in logs2
status 0
./errcount.sh: line 13: cd: missing: No such file or directory
errcount.sh: line 13: "cd -- "$dir"" failed with status 1
status 1

How each piece contributes:

  • ${1:-} lets the script test for a missing argument itself instead of dying with $1: unbound variable, so the user sees a usage message and status 2.
  • nullglob (lesson 52) makes *.log expand to nothing in an empty folder, so the array is empty rather than holding the literal text *.log.
  • grep -c ... || true treats a zero count as a normal result. Without || true, web.log would have stopped the script.
  • total=$(( total + n )) is an assignment, which never fails because of the arithmetic result, unlike (( total += n )) when the sum is 0.
  • The failed cd is a real error. set -e stops the script, and the ERR trap adds the line number and the failing command after cd's own message.
  • -E and inherit_errexit do not change the output of this small script, but they keep the behavior the same if the loop body is later moved into a function or a command substitution.

The examples were run with Bash 5.2.21 and GNU coreutils 9.4 on Ubuntu 24.04. Error messages from Bash show the script name and line number when they come from a script file.

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 Combining Strict Mode Options Safely and get answers drawn from it.

Signed-in readers only.