Handling Errors with if Statements
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:
diekeeps 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 -scompares 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.