Handling Errors with if Statements

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

An if statement in Bash does not test a true-or-false value the way it does in most programming languages. It runs a command and looks at that command's exit status (lesson 116): status 0 runs the then branch, any other status runs the else branch. Because every command reports success or failure this way, if is the most direct tool for handling errors. You run the risky command as the condition and decide right there what happens when it fails.

This lesson builds on lesson 66 (the if syntax) and lesson 117 ($?). It focuses on using if deliberately for error handling: reacting to failures, keeping the real status, telling different failures apart, and writing scripts that explain what went wrong.

The Command Is the Condition

The simplest form puts the command itself after if:

if mkdir -p backup; then echo "backup folder ready"; fi
if cp nofile.txt backup/; then echo copied; else echo "copy failed"; fi
backup folder ready
cp: cannot stat 'nofile.txt': No such file or directory
copy failed

There are no brackets here. [ ] and [[ ]] are themselves commands that test strings, numbers and files (lessons 68-69). When the thing you want to check is "did this command work?", you run the command directly. Writing if [ cp nofile.txt backup/ ] would not run cp at all; it would ask [ to evaluate the words as a test expression.

Notice also that cp printed its own message to standard error. The if statement did not suppress it, and in many cases you want to keep it, because it says why the copy failed. Your own message can then say what that means for the script.

Reacting Only to Failure: if !

Most error handling only cares about the failure case. The ! operator inverts the status, so the then branch runs when the command fails:

if ! cp nofile.txt backup/ 2>/dev/null; then
    echo "error: could not copy nofile.txt" >&2
fi
error: could not copy nofile.txt

The pattern almost always ends the script or the function inside the branch:

if ! cd -- "$dir"; then
    echo "cannot enter $dir, nothing changed" >&2
    exit 1
fi

With dir=/nonexistent this printed:

cdx2.sh: line 2: cd: /nonexistent: No such file or directory
cannot enter /nonexistent, nothing changed

and the script ended with status 1. Stopping here matters: every command after a failed cd would otherwise run in the wrong directory.

$? Inside an if ! Branch Is Always 0

! changes the status that if sees, and $? reflects the changed status. Inside the then branch of if !, $? is therefore 0, not the command's real status:

if ! cp nofile.txt backup/ 2>/dev/null; then echo "status in branch: $?"; fi
if cp nofile.txt backup/ 2>/dev/null; then :; else echo "status in else: $?"; fi
status in branch: 0
status in else: 1

When the status itself is needed, either use the else branch of a positive if (the : command does nothing and fills the empty then branch), or capture the status before testing it, as shown below.

The Short Form: || and Grouping

For a single reaction, the || operator (lesson 65) is shorter than an if block:

cd /nonexistent || exit
echo "not reached"

A bare exit uses the status of the last command, so the script ended with the status of the failed cd, which was 1.

To run several commands on failure, group them with braces:

cp nofile.txt backup/ 2>/dev/null || { echo "copy failed" >&2; exit 3; }
echo "not reached"
copy failed

The script ended with status 3. Braces need a space after { and a ; (or newline) before }. Parentheses look similar but run the group in a subshell, so exit leaves only that subshell:

cp nofile.txt backup/ 2>/dev/null || ( echo "copy failed" >&2; exit 3 )
echo "still running after subshell exit"
copy failed
still running after subshell exit

The script continued and ended with status 0, which is exactly the kind of silent failure error handling is supposed to prevent.

Why a && b || c Is Not if/then/else

a && b || c looks like "if a then b else c", but c also runs when a succeeds and b fails:

true && false || echo "c ran even though a succeeded"
c ran even though a succeeded

When there are two outcomes and both branches contain real work, write a full if/else. Reserve || for "do this, or else react to the failure".

Capturing Output and Status Together

A command substitution in an assignment passes its status through to the assignment (lesson 117), so the assignment can be the condition:

if out=$(ls /nonexistent 2>&1); then
    echo "ok: $out"
else
    echo "ls failed ($?): $out"
fi
ls failed (2): ls: cannot access '/nonexistent': No such file or directory

2>&1 inside the substitution captured the error message into out as well, so the script decides where and how to show it. In the else branch, $? still holds the status of ls, because the condition was not negated.

This only works with a plain assignment. With local, export, declare or readonly in front, the status is that of the builtin, which succeeds:

f() { if local x=$(false); then echo "local hides failure"; fi; }
f
local hides failure

Inside functions, declare first and assign in the condition: local x; if x=$(cmd); then ....

Telling Different Failures Apart

Many commands use different non-zero statuses for different problems. grep is a common example: 0 means a match was found, 1 means no match, 2 means an error such as an unreadable file. A plain if merges 1 and 2:

printf 'user=alice\nport=8080\n' > app.conf
if grep -q '^port=' missing.conf; then echo found; else echo "not found or error ($?)"; fi
grep: missing.conf: No such file or directory
not found or error (2)

To handle each status separately, run the command, then examine $? immediately with case:

check() {
    grep -q "^$1=" "$2" 2>/dev/null
    case $? in
        0) echo "$1: present in $2" ;;
        1) echo "$1: missing from $2" ;;
        *) echo "$1: cannot read $2" >&2; return 2 ;;
    esac
}
check port app.conf
check host app.conf
check port missing.conf; echo "check returned $?"
port: present in app.conf
host: missing from app.conf
port: cannot read missing.conf
check returned 2

case $? must come directly after the command, before any other command replaces $?. If the status is needed in more than one place, save it first with rc=$?. Under set -e (lesson 119), use rc=0; grep -q ... || rc=$? so that the "no match" status does not stop the script before case sees it.

Checking Conditions Before Acting

Not every error comes from a command that already ran. Often the script should check its inputs first and refuse to start. Test commands combined with elif (lesson 67) give a precise message for each case:

f=$1
if [[ ! -e $f ]]; then echo "$f: does not exist"
elif [[ ! -f $f ]]; then echo "$f: not a regular file"
elif [[ ! -s $f ]]; then echo "$f: empty"
else echo "$f: $(wc -l < "$f") lines"; fi

Run with an existing file, an empty file, a directory and a missing name:

app.conf: 2 lines
empty.txt: empty
backup: not a regular file
nothing: does not exist

The order matters: each test assumes the previous ones passed. Checking existence first means the later messages never describe a file that is not there.

Checking first does not replace checking the command afterwards. Between the test and the action, another process could delete the file, or the action could fail for a reason no test anticipated, such as a full disk. Use the pre-checks for clear messages and still test the command that does the work.

if and set -e

Commands in an if condition are exempt from set -e, which is what makes if usable in strict scripts:

set -e
if grep -q ERROR app.conf; then echo "has errors"; else echo "no errors, script continues"; fi
no errors, script continues

The exemption reaches into everything the condition runs, including functions. A function that relies on set -e to stop at its first failure does not stop when it is called from an if:

set -e
setup() { false; echo "setup kept going"; }
if setup; then echo "setup reported success"; fi
setup kept going
setup reported success

false failed, but the function continued and returned the status of its last command, echo. Functions that are meant to be tested with if should handle their own failures explicitly:

set -e
setup() {
    mkdir -p work || return 1
    cp nofile.txt work/ || return 1
    echo "setup done"
}
if ! setup; then echo "setup failed" >&2; exit 1; fi
echo "not reached"
cp: cannot stat 'nofile.txt': No such file or directory
setup failed

The script ended with status 1. With || return 1 after each step, the function reports failure correctly whether or not set -e is active and however it is called.

Retrying a Failing Command

if inside a loop gives a simple retry policy: try, stop on success, give up after a limit. Here flaky stands in for a network command that fails twice and then works:

attempt=1
max=3
n=0
flaky() { n=$((n+1)); [ "$n" -ge 3 ]; }
while true; do
    if flaky; then echo "succeeded on attempt $attempt"; break; fi
    if (( attempt >= max )); then echo "giving up after $max attempts" >&2; exit 1; fi
    echo "attempt $attempt failed, retrying"
    attempt=$((attempt + 1))
done
attempt 1 failed, retrying
attempt 2 failed, retrying
succeeded on attempt 3

In real scripts a sleep before the next attempt gives the remote side time to recover. Lesson 87 covers limits that keep such loops from running forever.

A Complete Example

This script installs a configuration file into a directory. It checks its arguments, creates the directory if needed, skips the work when the file is already current, keeps a backup of the old version, and verifies the copy. Each step is an if that either continues or stops with a message saying what happened to the system:

#!/usr/bin/env bash
# install-conf.sh SOURCE DEST_DIR: copy a config file, keeping a backup of the old one
prog=${0##*/}

die() {
    echo "$prog: $1" >&2
    exit "${2:-1}"
}

if (( $# != 2 )); then
    die "usage: $prog SOURCE DEST_DIR" 2
fi
src=$1
dest_dir=$2
name=${src##*/}
target=$dest_dir/$name

if [[ ! -f $src ]]; then
    die "source '$src' is not a regular file"
fi

if [[ ! -d $dest_dir ]]; then
    if ! mkdir -p -- "$dest_dir"; then
        die "cannot create '$dest_dir'"
    fi
    echo "created $dest_dir"
fi

if [[ -e $target ]]; then
    if cmp -s -- "$src" "$target"; then
        echo "$target is already up to date"
        exit 0
    fi
    if ! cp -p -- "$target" "$target.bak"; then
        die "cannot back up '$target'; nothing was changed"
    fi
    echo "backed up old $name to $target.bak"
fi

if ! cp -- "$src" "$target"; then
    die "copy to '$target' failed"
fi

if ! cmp -s -- "$src" "$target"; then
    die "verification failed: '$target' differs from '$src'"
fi
echo "installed $target"

A test session, changing app.conf between the third and fourth installs and finally using a regular file named afile where a directory is expected:

./install-conf.sh;                      echo "status $?"
./install-conf.sh nope.conf etc;        echo "status $?"
./install-conf.sh app.conf etc;         echo "status $?"
./install-conf.sh app.conf etc;         echo "status $?"
printf 'port=9090\n' > app.conf
./install-conf.sh app.conf etc;         echo "status $?"
touch afile
./install-conf.sh app.conf afile/sub;   echo "status $?"
install-conf.sh: usage: install-conf.sh SOURCE DEST_DIR
status 2
install-conf.sh: source 'nope.conf' is not a regular file
status 1
created etc
installed etc/app.conf
status 0
etc/app.conf is already up to date
status 0
backed up old app.conf to etc/app.conf.bak
installed etc/app.conf
status 0
mkdir: cannot create directory 'afile': Not a directory
install-conf.sh: cannot create 'afile/sub'
status 1

After the fifth run, etc/app.conf held port=9090 and etc/app.conf.bak held the previous port=8080.

Points to notice:

  • die keeps every failure path to one line and gives the script a consistent message format and exit status (2 for usage errors, 1 for everything else). Lesson 125 develops this idea.
  • cmp -s compares two files silently and returns 0 when they are identical, so it serves both as the "already up to date" check and as the final verification.
  • Each failure message says what state the system was left in ("nothing was changed"), which is what the person running the script needs to know next.
  • mkdir's own message explains why the directory could not be created; the script's message says what it was trying to do. Both are kept.
  • -- before file names protects against names that start with - (lesson 111).

The examples were run with Bash 5.2.21, GNU grep 3.11, GNU coreutils 9.4 and GNU diffutils 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 Handling Errors with if Statements and get answers drawn from it.

Signed-in readers only.