Bash error handling is off by default. When a command fails, bash prints the error, sets $? and happily runs the next line, which is how a failed cd turns into an rm in the wrong directory, or a failed download turns into a deploy of an empty file. Adding set -euo pipefail at the top fixes most of that, but not all of it, and the gaps are exactly where scripts surprise you in production. This guide explains what each option really does, the cases where set -e quietly does nothing, how to report the failing command and line with trap ERR, how to clean up reliably with trap EXIT, and ends with a complete script template. Every script was checked with ShellCheck and run on bash 5.2 on Ubuntu; differences on the bash 3.2 that ships with macOS are noted.

From my own work: Most broken cron jobs I have debugged on client servers had no error handling at all: a backup script whose mysqldump failed every night for weeks while the following gzip and upload steps succeeded on an empty file. The log showed success because the last command succeeded. Strict mode plus an ERR trap would have turned the first failure into an alert.
The problem: bash keeps going after errors
Here is what happens without any error handling. Every line runs, and the script exits with status 0 because the last command succeeded:
#!/usr/bin/env bash
# no-strict.sh - what bash does by default when a command fails
cp /nonexistent/config.ini /tmp/app.ini
echo "cp failed with status $?, but the script keeps going"
grep -c "^port" /tmp/app.ini
echo "and now we would deploy with a missing config"
$ bash no-strict.sh; echo "exit status: $?"
cp: cannot stat '/nonexistent/config.ini': No such file or directory
cp failed with status 1, but the script keeps going
grep: /tmp/app.ini: No such file or directory
and now we would deploy with a missing config
exit status: 0
A cron job or CI step that runs this script reports success. That exit status is the real danger: monitoring, && chains and systemd all trust it.
set -euo pipefail explained
The common strict-mode line combines three separate options, all documented under the set builtin in the GNU Bash manual:
| Option | Long form | What it does | Without it |
|---|---|---|---|
-e |
-o errexit |
Exit when a command returns non-zero (with exceptions, see below) | Failures are printed and ignored |
-u |
-o nounset |
Treat expanding an unset variable as an error | $TARGET_DIR silently becomes an empty string |
-o pipefail |
none | A pipeline’s status is the last non-zero status in it | Only the last command of a pipeline counts |
-E |
-o errtrace |
Functions, command substitutions and subshells inherit the ERR trap | trap ERR does not fire inside functions |
This script shows pipefail and nounset in action:
#!/usr/bin/env bash
set -e
false | true
echo "without pipefail the pipeline status is $?"
set -o pipefail
if ! false | true; then
echo "with pipefail the failure of 'false' is reported"
fi
set -u
name="${1:-world}" # default value: safe with set -u
echo "hello $name"
echo "deploying to $TARGET_DIR" # typo or missing variable
echo "never printed"
$ bash strict-demo.sh
without pipefail the pipeline status is 0
with pipefail the failure of 'false' is reported
hello world
strict-demo.sh: line 12: TARGET_DIR: unbound variable
$ echo $?
1
Two details matter in practice. First, set -u needs a default for anything that may legitimately be unset: use ${1:-default} for optional arguments and ${VAR:-} to test an optional environment variable. Second, pipefail changes the status of pipelines such as producer | head -1: when head exits early, the producer can be killed by SIGPIPE and the pipeline reports status 141. If you hit that, restructure the command or handle that specific case.
Where set -e silently does nothing
set -e is ignored in several contexts by design. The rule from the manual: the shell does not exit if the failing command is part of the condition of an if, while or until, part of a && or || list except the last command, or inverted with !. What surprises people is that the rule also applies to everything inside a function called in such a context. The BashFAQ/105 collects many more examples. These four catch most teams:
#!/usr/bin/env bash
set -euo pipefail
check_disk() {
false # a failing command inside a function
echo " check_disk kept running after false"
}
echo "1. called as a condition:"
if check_disk; then echo " the if saw success"; fi
echo "2. on the left of ||:"
check_disk || echo " never printed"
echo "3. local hides the status of a command substitution:"
load() { local out=$(false); echo " local out=$(false) returned $?"; }
load
echo "4. arithmetic that evaluates to 0:"
count=0
((count++))
echo " never printed: ((count++)) returned 1 and set -e exited"
$ bash pitfalls.sh; echo "exit status: $?"
1. called as a condition:
check_disk kept running after false
the if saw success
2. on the left of ||:
check_disk kept running after false
3. local hides the status of a command substitution:
local out=$(false) returned 0
4. arithmetic that evaluates to 0:
exit status: 1
- Functions used as conditions. Inside
check_disk,falsedid not stop anything because the function was called from anif. The function then returned the status of its last command,echo, so the caller saw success. Write functions that are used in conditions with explicit checks, for examplefalse || return 1, orreturna status deliberately. local var=$(cmd). The status of the line is the status oflocal, which succeeds. Declare and assign on separate lines:local out; out=$(cmd). ShellCheck flags this as SC2155.((count++))whencountis 0. The expression evaluates to 0, so the command returns 1 and the script exits. Usecount=$((count + 1)). The macOS bash 3.2 does not exit here, which is one reason a script can behave differently on a laptop and on a server.- Command substitution inside another command. In
echo "version: $(get_version)"the failure is lost because the status of the line is the status ofecho. Assign to a variable first, as shown in theinherit_errexitsection.
None of this means you should drop set -e. It catches most failures in straight-line code, and the traps below make the rest visible. Just do not rely on it inside functions that you call from conditions.
trap ERR: report the failing command, line and call stack
When a strict script exits, you want to know which command failed and where. The ERR trap runs whenever a command fails in a context where set -e would exit. $BASH_COMMAND holds the command being executed, $LINENO the line, and the FUNCNAME, BASH_SOURCE and BASH_LINENO arrays describe the call stack (Bash Variables). The -E option makes the trap fire inside functions too:
#!/usr/bin/env bash
set -Eeuo pipefail
on_error() {
local status=$? line=$1 cmd=$2
echo "ERROR: '$cmd' failed with status $status at line $line" >&2
local i
for ((i = 1; i < ${#FUNCNAME[@]}; i++)); do
echo " at ${FUNCNAME[$i]}() in ${BASH_SOURCE[$i]}:${BASH_LINENO[$((i - 1))]}" >&2
done
}
trap 'on_error "$LINENO" "$BASH_COMMAND"' ERR
fetch_release() {
curl -fsS --max-time 5 "https://example.invalid/release.tar.gz" -o /tmp/release.tar.gz
}
deploy() {
echo "deploying..."
fetch_release
echo "never printed"
}
deploy
$ bash err-trap.sh
deploying...
curl: (6) Could not resolve host: example.invalid
ERROR: 'curl -fsS --max-time 5 "https://example.invalid/release.tar.gz" -o /tmp/release.tar.gz' failed with status 6 at line 15
at fetch_release() in err-trap.sh:15
at deploy() in err-trap.sh:20
at main() in err-trap.sh:24
$ echo $?
6
The first statement of on_error must read $?; any command before it would overwrite the failing status. The trap only reports, it does not change the outcome: set -e still exits with the original status, 6 here, which is curl’s code for a DNS failure. On bash 3.2, $LINENO inside the trap can point at the start of the function instead of the failing line, one more reason to run scripts with a current bash.
trap EXIT: cleanup that always runs and keeps the status
The EXIT trap runs when the script ends for any reason: normal completion, a set -e exit, an explicit exit or a signal you trap. That makes it the right place to delete temporary files, release locks and restore state (trap in the Bash manual):
#!/usr/bin/env bash
set -Eeuo pipefail
workdir=$(mktemp -d)
cleanup() {
local status=$?
rm -rf "$workdir"
echo "cleanup done, exiting with status $status" >&2
exit "$status"
}
trap cleanup EXIT
trap 'exit 130' INT # Ctrl+C: 128 + SIGINT (2)
trap 'exit 143' TERM # kill or systemctl stop: 128 + SIGTERM (15)
echo "working in $workdir"
printf 'id,totaln1,42n' > "$workdir/report.csv"
cp "$workdir/report.csv" "${OUT_DIR:-/nonexistent}/report.csv"
echo "report copied"
$ bash exit-trap.sh; echo "exit status: $?"
working in /tmp/tmp.1j1qneYmab
cp: cannot create regular file '/nonexistent/report.csv': No such file or directory
cleanup done, exiting with status 1
exit status: 1
$ OUT_DIR=/tmp bash exit-trap.sh; echo "exit status: $?"
working in /tmp/tmp.2XTvvdhN9G
report copied
cleanup done, exiting with status 0
exit status: 0
- Save
$?first and exit with it. Otherwise the status of the last cleanup command becomes the script’s status, and a failed run can look successful. - Create temporary files with
mktemp, never fixed names in/tmp, so parallel runs cannot collide and other users cannot pre-create the file. - Trap INT and TERM and convert them to an exit. The EXIT trap then runs on Ctrl+C and on
systemctl stop, and the status follows the convention of 128 plus the signal number, so callers can tell an interruption from a failure. - Keep cleanup idempotent.
rm -rf "$workdir"andrm -fdo not fail if the files are already gone.
For jobs that must never overlap, such as a backup started by a timer, use flock from util-linux rather than a hand-made lock file, which is easy to get wrong when a script crashes. With cron, wrap the command as flock -n /run/lock/backup.lock /usr/local/bin/backup.sh. A systemd timer gives you that overlap protection for free, as explained in systemd timers vs cron.
Handling expected failures without disabling strict mode
Some commands use a non-zero status for normal results. grep returns 1 when nothing matches, diff returns 1 when files differ, and test returns 1 when a condition is false. Handle those explicitly instead of turning set -e off around them:
#!/usr/bin/env bash
set -euo pipefail
log=$(mktemp)
printf 'INFO startnINFO donen' > "$log"
# grep exits 1 when nothing matches, which set -e treats as a failure
errors=$(grep -c ERROR "$log" || true)
echo "errors: $errors"
if grep -q WARN "$log"; then
echo "warnings found"
else
echo "no warnings"
fi
# expected non-zero statuses: capture them explicitly
status=0
diff <(echo a) <(echo b) > /dev/null || status=$?
echo "diff status: $status (1 means the inputs differ)"
rm -f "$log"
$ bash expected.sh
errors: 0
no warnings
diff status: 1 (1 means the inputs differ)
cmd || trueaccepts any failure. Use it only when you have checked that every failure mode is harmless;grep -cabove still prints its count, so the variable is correct.if cmd; thenis the clearest form when you branch on the result.cmd || status=$?captures the exact status so you can tell “differs” (1) from “error” (2).
Retrying flaky commands with backoff
Network calls, package mirrors and APIs fail transiently. A small retry function keeps strict mode intact and makes the retry policy visible in one place:
#!/usr/bin/env bash
set -euo pipefail
# retry ATTEMPTS DELAY COMMAND [ARGS...] - doubles the delay after each failure
retry() {
local attempts=$1 delay=$2 n=1
shift 2
until "$@"; do
if ((n >= attempts)); then
echo "giving up after $n attempts: $*" >&2
return 1
fi
echo "attempt $n failed, retrying in ${delay}s: $*" >&2
sleep "$delay"
n=$((n + 1))
delay=$((delay * 2))
done
}
retry 3 1 curl -fsS --max-time 5 -o /dev/null https://example.com/ && echo "example.com is up"
retry 3 1 test -f /tmp/does-not-exist || echo "file never appeared, handling it"
$ bash retry.sh
example.com is up
attempt 1 failed, retrying in 1s: test -f /tmp/does-not-exist
attempt 2 failed, retrying in 2s: test -f /tmp/does-not-exist
giving up after 3 attempts: test -f /tmp/does-not-exist
file never appeared, handling it
Because the command runs as the condition of until, set -e does not apply inside it. That is fine for external programs such as curl, which report their own status, but if you retry one of your own shell functions, make that function return a non-zero status explicitly on failure. Retry only operations that are safe to repeat. The reasoning behind doubling delays and adding jitter is the same as in retry with exponential backoff and jitter.
inherit_errexit: failures inside command substitution
By default, a command substitution $(...) runs in a subshell that does not inherit set -e, so a failing command in the middle is ignored and the substitution returns the status of its last command. Bash 4.4 added shopt -s inherit_errexit to change that (The Shopt Builtin):
#!/usr/bin/env bash
set -euo pipefail
shopt -s inherit_errexit # bash 4.4+; remove this line to see the difference
get_version() {
cat /nonexistent/VERSION # fails
echo "0.0.0" # without inherit_errexit this still runs
}
version=$(get_version)
echo "version: $version"
$ bash inherit.sh; echo "exit status: $?" # with shopt -s inherit_errexit
cat: /nonexistent/VERSION: No such file or directory
exit status: 1
$ bash inherit-off.sh; echo "exit status: $?" # same script without the shopt line
cat: /nonexistent/VERSION: No such file or directory
version: 0.0.0
exit status: 0
Note the assignment on its own line, version=$(get_version). Only a plain assignment passes the substitution’s status through; inside echo or after local it is lost even with inherit_errexit. The option does not exist in bash 3.2, so the template below enables it only where it is available.
A complete bash script template
This template puts everything together in a real task: archive a directory, verify the archive, publish it atomically and keep the newest N copies. It validates arguments, checks for required commands, logs with timestamps to stderr, reports the failing line through the ERR trap and removes a half-written archive through the EXIT trap:
#!/usr/bin/env bash
# backup-site.sh - archive a directory with strict error handling
# usage: backup-site.sh SOURCE_DIR DEST_DIR [KEEP]
set -Eeuo pipefail
shopt -s inherit_errexit 2>/dev/null || true # bash 4.4+, ignored on older bash
readonly SCRIPT=${0##*/}
tmp=""
log() { printf '%s %s: %sn' "$(date '+%F %T')" "$SCRIPT" "$*" >&2; }
die() { log "ERROR: $*"; exit 1; }
on_error() {
local status=$?
log "ERROR: '$2' failed with status $status at line $1"
}
cleanup() {
local status=$?
[[ -n $tmp ]] && rm -f "$tmp"
((status == 0)) || log "finished with errors (status $status)"
exit "$status"
}
trap 'on_error "$LINENO" "$BASH_COMMAND"' ERR
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
require() {
local cmd
for cmd in "$@"; do
command -v "$cmd" > /dev/null || die "missing command: $cmd"
done
}
main() {
(($# >= 2)) || die "usage: $SCRIPT SOURCE_DIR DEST_DIR [KEEP]"
local src=$1 dest=$2 keep=${3:-7}
[[ -d $src ]] || die "source is not a directory: $src"
[[ $keep =~ ^[0-9]+$ ]] || die "KEEP must be a number: $keep"
require tar gzip
mkdir -p "$dest"
local name archive
name="$(basename "$src")-$(date +%Y%m%d-%H%M%S).tar.gz"
archive="$dest/$name"
tmp="$archive.part"
log "archiving $src to $archive"
tar -czf "$tmp" -C "$(dirname "$src")" "$(basename "$src")"
gzip -t "$tmp" # verify before publishing the file
mv "$tmp" "$archive"
tmp=""
# keep the newest KEEP archives, delete the rest
local old
# shellcheck disable=SC2012 # names are generated by this script
old=$(ls -1t "$dest"/*.tar.gz | tail -n +$((keep + 1)))
if [[ -n $old ]]; then
log "removing $(wc -l <<< "$old" | tr -d ' ') old archive(s)"
xargs rm -f -- <<< "$old"
fi
log "done: $(du -h "$archive" | cut -f1) written"
}
main "$@"
$ ./backup-site.sh site out 2
2026-11-29 10:36:29 backup-site.sh: archiving site to out/site-20261129-103629.tar.gz
2026-11-29 10:36:29 backup-site.sh: removing 1 old archive(s)
2026-11-29 10:36:29 backup-site.sh: done: 4.0K written
$ ./backup-site.sh site /proc/x
mkdir: cannot create directory ‘/proc/x’: No such file or directory
2026-11-29 10:36:29 backup-site.sh: ERROR: 'mkdir -p "$dest"' failed with status 1 at line 43
2026-11-29 10:36:29 backup-site.sh: finished with errors (status 1)
- Write to a
.partfile, verify, thenmv. A rename on the same filesystem is atomic, so the destination never contains a half-written archive, and the EXIT trap deletes the partial file on failure. - Put the logic in
main()and call it on the last line. Bash reads a script while it runs it, so editing a running script can break it. With everything inside functions and the single call at the end, bash has parsed the whole file before any work starts. - Log to stderr. stdout stays clean for data, and cron or systemd capture stderr in the journal.
The same structure works for database dumps; automated MySQL backups on a VPS shows a dump script that benefits directly from pipefail, because mysqldump | gzip otherwise reports gzip’s success even when the dump failed. For off-site copies, pair it with restic backups to S3 or Google Drive.
Lint every script with ShellCheck
ShellCheck finds most of the problems in this guide before the script ever runs: unquoted variables, local masking return values, cd without error handling, and more. Install it with sudo apt install shellcheck or brew install shellcheck, run shellcheck script.sh, and add it to CI so new scripts cannot merge with warnings. When a warning is a deliberate choice, disable it on that one line with a comment explaining why, as the template does for ls.
Bash error handling checklist
#!/usr/bin/env bashandset -Eeuo pipefailat the top.shopt -s inherit_errexiton bash 4.4 and newer.trap ERRlogging the command, line and stack;$?read first.trap EXITcleanup that exits with the saved status; INT and TERM trapped.mktempfor temporary files;.partfiles andmvfor outputs.- Defaults for optional variables:
${1:-},${VAR:-default}. local var; var=$(cmd), neverlocal var=$(cmd).- Expected failures handled with
if,|| trueor|| status=$?. - No reliance on
set -einside functions used as conditions. - ShellCheck clean, in CI.
Want this done on your own server or site?
I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.
FAQ
What does set -euo pipefail do in bash?
set -e exits the script when a command fails, set -u treats unset variables as errors, and set -o pipefail makes a pipeline fail if any command in it fails rather than only the last one. Together they stop most scripts at the first real error instead of continuing with bad data.
Why does set -e not exit when a command fails inside a function?
If the function is called as part of an if, while or until condition, after ! or on the left side of && or ||, set -e is ignored for everything inside it, including nested commands. The function then returns the status of its last command. Return explicit statuses from such functions.
How do I get the line number of an error in a bash script?
Use set -E and an ERR trap such as trap ‘on_error “$LINENO” “$BASH_COMMAND”‘ ERR. Inside the handler, read $? first to get the status, and use the FUNCNAME, BASH_SOURCE and BASH_LINENO arrays to print the call stack.
How do I run cleanup code when a bash script exits?
Define a cleanup function, save $? at its start, remove temporary files, then exit with the saved status, and register it with trap cleanup EXIT. Also trap INT and TERM and convert them to exit 130 and exit 143 so cleanup runs on Ctrl+C and on service stops.
How do I ignore an expected error with set -e?
Use command || true when any failure is harmless, if command; then for branching, or command || status=$? to capture the exact exit code. For example grep exits 1 when nothing matches, so count=$(grep -c ERROR file || true) still returns the count.
Sources
- GNU Bash manual: The Set Builtin
- GNU Bash manual: Bourne Shell Builtins (trap)
- GNU Bash manual: The Shopt Builtin
- GNU Bash manual: Bash Variables
- BashFAQ/105: Why does set -e not do what I expected?
- ShellCheck wiki: SC2155

Saizul Amin is a web developer, AI automation engineer and technical SEO consultant from Dhaka, Bangladesh (B.Sc. in CSE, BUBT). Since 2017 he has worked in digital marketing, WordPress, IT infrastructure and server administration, including the bilingual SHR Bangladesh website for DGHS, WordPress sites for UK and US clients, and the ShobFree tools platform. He runs this blog on his own Ubuntu VPS with nginx, Redis and CloudPanel, and tests the guides here on it. Portfolio: saizul.com

