Fail-Fast Scripts with set -e: Benefits and Caveats

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 119 of 205

By default, Bash keeps running a script after a command fails. The failed command prints its error, its exit code is stored in $?, and the next line runs as if nothing had happened. set -e changes that: when a command fails, the shell stops the script immediately, with the failed command's exit code. This "fail fast" behavior prevents a script from carrying on in a broken state, but its exact rules contain many exceptions, and understanding them is the difference between a safety net and a false sense of security.

#!/usr/bin/env bash
echo "start"
cp nofile x
echo "reached without set -e"
start
cp: cannot stat 'nofile': No such file or directory
reached without set -e

The script continues past the failure and ends with status 0. With set -e added:

#!/usr/bin/env bash
set -e
echo "start"
cp nofile x
echo "not reached"
start
cp: cannot stat 'nofile': No such file or directory

The script stops at the failed cp and its exit code is 1, the status of cp.

Why Fail Fast

Commands in a script usually depend on each other. If one step fails and the script keeps going, later steps work with missing or wrong data:

cd /srv/build
rm -rf ./*

If cd fails (the directory does not exist, or a permission is missing), the rm runs in whatever directory the script started in. With set -e, the failed cd ends the script before rm runs. Lesson 160 returns to this kind of danger.

The benefits:

  • A failure stops the script close to its cause, so the last error message on the screen is usually the relevant one.
  • The script's exit code reports the failure to cron, CI systems and calling scripts (lesson 116), instead of the status of some later command that happened to succeed.
  • Short scripts get basic error handling without an || exit after every line.

Turning It On and Off

set -e            # short form
set -o errexit    # long form, same effect
set +e            # turn it off again

The option applies from the line where it is set. It can be turned off for a section and on again:

set -e
set +e
false
echo "set +e turned it off"
set -e
false
echo "not reached"
set +e turned it off

The special parameter $- lists the shell's single-letter options. When set -e is active, it contains e:

set -e
echo "$-"
ehB

The Shebang Form

Some scripts put the option in the first line, #!/bin/bash -e. It works when the script is run as a program, but the line is only a comment when the script is passed to bash explicitly:

printf '#!/bin/bash -e\nfalse\necho "reached when run with bash file"\n' > e30.sh
chmod +x e30.sh
./e30.sh;     echo "direct: $?"
bash e30.sh;  echo "via bash: $?"
direct: 1
reached when run with bash file
via bash: 0

A set -e line inside the script applies however the script is started (lesson 28), so it is the more reliable place.

When set -e Does Not Stop the Script

The Bash manual lists the situations in which a failure is ignored even with set -e. They exist because in these places a non-zero status is part of normal logic, not an error. Each one is shown below with the result from a test run.

Conditions of if, while and until

A command tested by if, elif, while or until is expected to fail sometimes; that is the point of the test:

set -e
if cp nofile x 2> /dev/null; then
    echo "copied"
else
    echo "if condition failure ok"
fi
echo "continues"
if condition failure ok
continues

Commands in && and || Lists, Except the Last

In a && b and a || b, the commands before the last operator may fail without ending the script:

set -e
cp nofile x 2> /dev/null || echo "|| handled"
false && echo "no"
echo "continues"
|| handled
continues

false && echo no fails as a whole, but false is not the last command of the list, so the script continues. The last command of a list is checked:

set -e
true && false
echo "not reached"

The script ends with status 1 at false.

This rule produces one of the best-known surprises. The line [ -f nofile ] && echo exists fails when the file is missing, but because the failing test is not the last command in the list, the script continues. Put the same line at the end of a function, however, and the function returns that failure as its own status:

set -e
check() {
    [ -f nofile ] && echo "exists"
}
check
echo "after check"

The script ends at check with status 1, and after check is never printed. The function call itself is a simple command that failed. Writing the test as an if statement, or ending the function with return 0, avoids the problem.

Negation with !

set -e
! true
echo "! true does not exit"
! true does not exit

A command whose status is inverted with ! never triggers set -e, whatever the result.

Pipelines: Only the Last Command

The status of a pipeline is the status of its last command (lesson 61), and set -e looks only at that:

set -e
false | true
echo "pipeline: only last counts"
pipeline: only last counts

true | false would end the script. A failure in the middle of a pipeline, such as grep finding nothing before sort, is ignored unless set -o pipefail is also set (lesson 120).

Functions Called in a Condition

When a function is called where set -e is ignored (in an if condition, or on the left of && or ||), the option is ignored for every command inside the function as well:

set -e
f() {
    false
    echo "inside f after false"
}
if f; then echo "f ok"; fi
echo "end"
inside f after false
f ok
end

The false inside f did not stop anything, and f returned 0 because its last command, echo, succeeded. Called on its own line, the same function ends the script at its first command:

set -e
f() {
    false
    echo "inside f after false"
}
f
echo "end"

Nothing is printed, and the status is 1. The same function behaves in two different ways depending on where it is called, which is why a function that must handle errors should check them explicitly rather than rely on set -e.

The same rule covers a group: { false; echo "group continues"; } || echo "group failed" prints group continues, because the group is on the left of ||.

Failures That Are Hidden

Some failures are not seen by set -e because another command's status replaces them.

local, export and declare

Lesson 117 showed that local x=$(cmd) reports the status of local, not of cmd. Under set -e, the failure of cmd is therefore ignored:

set -e
f() {
    local x=$(false)
    echo "local hides: continues"
}
f
local hides: continues

export V=$(false) behaves the same way. A plain assignment keeps the status, and does stop the script:

set -e
x=$(false)
echo "not reached"

Declare first and assign on a separate line (local x then x=$(cmd)) to keep the protection.

Command Substitution Inside Another Command

When $( ) appears as an argument of another command, only the outer command's status counts:

set -e
echo "value: $(false; echo inside)"
echo "cmdsub in argument: continues"
value: inside
cmdsub in argument: continues

Commands Inside Command Substitution

By default, the commands inside $( ) do not inherit set -e. The false below does not stop the subshell, and the assignment gets the status of the last command, echo:

set -e
x=$(false; echo "inside cmdsub continues")
echo "x=$x"
x=inside cmdsub continues

Bash 4.4 added the inherit_errexit option. With shopt -s inherit_errexit, the subshell stops at false, the assignment fails, and the script ends with status 1. Ordinary subshells in parentheses ( ... ) do inherit set -e without the option.

When set -e Stops a Script That Is Working Correctly

The opposite problem also occurs: set -e ends a script on a non-zero status that was not an error at all.

Commands That Use Status 1 as an Answer

grep returns 1 for "no match", diff returns 1 for "files differ", and grep -c returns 1 when the count is zero (lesson 116). Under set -e, such an answer ends the script:

set -e
count=$(grep -c gamma words.txt)
echo "count=$count"

The script ends at the assignment with status 1, and count=0 is never printed. Adding || true accepts the status:

set -e
count=$(grep -c gamma words.txt || true)
echo "count=$count"
count=0

|| true accepts every failure, including real errors such as a missing file. When the difference matters, save the status and check it (lesson 117):

set -e
rc=0
grep -q gamma words.txt || rc=$?
echo "rc=$rc"
rc=1

Now the script can treat 1 as "not found" and stop on 2.

Arithmetic That Evaluates to Zero

An arithmetic command (( expr )) returns 1 when the expression's value is 0 (lesson 73). (( i++ )) with i equal to 0 evaluates to the old value, 0, so it fails:

set -e
i=0
(( i++ ))
echo "not reached"

The script ends with status 1. (( ++i )) evaluates to the new value, 1, and i=$((i + 1)) is an assignment that always succeeds:

set -e
i=0
(( ++i ))
echo "++i ok i=$i"
++i ok i=1

Finding Out Where the Script Stopped

set -e ends the script silently: the only message is whatever the failed command printed, and some commands print nothing (grep -q, false, [ ]). An ERR trap (lesson 123) runs whenever a command fails in a place where set -e would act, which makes it a good place to report the location:

#!/usr/bin/env bash
set -e
trap 'echo "error on line $LINENO, status $?" >&2' ERR

cp nofile x 2> /dev/null
echo "not reached"
error on line 5, status 1

$LINENO holds the line number of the failing command, and $? its status. Lesson 126 covers tracing with bash -x, which shows every command as it runs.

Using set -e Sensibly

set -e is a safety net, not a full error handling strategy. Many experienced Bash authors use it; others avoid it because of the exceptions above. Both positions follow from the same facts:

  • It catches unexpected failures in straightforward sequences of commands, which is where most scripts spend most of their lines.
  • It does not catch failures in conditions, in && and || lists, in functions called from conditions, in the middle of pipelines, or behind local and export.
  • It stops scripts on status values that are answers rather than errors, unless those commands are written as conditions or followed by || true.

If you use it, combine it with explicit checks for the steps that matter most:

#!/usr/bin/env bash
set -e

src=$1
dest=$2

# a step whose failure needs a clear message: checked explicitly
if ! cd -- "$dest"; then
    echo "cannot enter $dest" >&2
    exit 1
fi

# a command whose "no match" status is a normal answer
if grep -q TODO -- "$src"; then
    echo "note: $src contains TODO items"
fi

# the remaining steps rely on set -e to stop on failure
cp -- "$src" .
gzip -f -- "${src##*/}"
echo "archived ${src##*/}.gz in $dest"

The cd and the grep are written as conditions, so their failures are handled where they occur. The copy and compression steps are plain commands; if either fails, set -e stops the script with the failing command's status. In a test with a source file that did not exist, grep printed its error and returned 2, the if treated that like "no TODO items", and the following cp failed and stopped the script with status 1.

Lesson 120 adds set -u and set -o pipefail, which close two of the gaps described here, and lesson 121 combines all three options.

The examples were run with Bash 5.2.21 and GNU coreutils 9.4. Error messages are shown as printed by the commands; Bash itself prints nothing when set -e ends a script.

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 Fail-Fast Scripts with set -e: Benefits and Caveats and get answers drawn from it.

Signed-in readers only.