On this page
- Why does a Bash script keep going after an error?
- What does set -e do, and where does it not apply?
- What do set -u and pipefail add?
- How do I clean up temp files on every exit?
- How do I report which line failed?
- How do I handle Ctrl+C and termination signals?
- How do I retry a flaky step and prevent overlapping runs?
- Which exit codes should my script return?
- Questions
Why does a Bash script keep going after an error?
By default Bash runs every line regardless of what happened before; a failing command only sets $?. That leads to classic accidents, where a failed cd leaves the script in the wrong folder and the next rm deletes the wrong files:
cd /srv/app/cache # fails if the folder is missing
rm -rf ./* # then runs in whatever folder we are inThe fix is to make failure stop the script, and to be explicit in the few places where a failure is acceptable. Three shell options do most of the work, usually written together as set -euo pipefail on the second line of the script. Each one has rules worth knowing, so they are explained one by one below, followed by traps for cleanup and reporting.
What does set -e do, and where does it not apply?
set -e (errexit) exits the script as soon as a simple command returns a non-zero status. It deliberately ignores failures where the script is already testing the result:
- the condition of
if,whileanduntil - any command before
&&or||except the last - commands negated with
!
#!/usr/bin/env bash
set -e
if grep -q deploy /etc/passwd; then echo "user exists"; fi # safe
rm /tmp/maybe-missing || true # failure allowed on purpose
count=$(grep -c ERROR app.log) || count=0
echo "errors: $count"grep -c exits 1 when it finds nothing, so the || count=0 keeps that normal case from ending the script. Two surprises: set -e is suspended inside a function called as an if condition, and local x=$(cmd) hides a failure of cmd. Write important checks explicitly rather than relying on errexit alone.
What do set -u and pipefail add?
set -u (nounset) turns a reference to an unset variable into an error, catching typos like $DEST_DRI before they expand to nothing. set -o pipefail makes a pipeline return the status of the last command that failed, instead of only the last command:
set -uo pipefail
echo "${1:-}" # safe: default for a missing argument
false | true; echo "status $?" # 1 with pipefail, 0 without
curl -fsS https://example.net/list.txt | sort > list.txtWithout pipefail, a failed download in the last line would still leave a successful status, because sort succeeded on empty input. With -u, give optional values a default (${VAR:-}) and check array length before expanding empty arrays on older Bash releases. One case to watch: head closing a pipe early can make the writer fail with SIGPIPE (status 141) under pipefail, so add || true to pipelines like yes | head -n 3.
How do I clean up temp files on every exit?
Register a function with trap ... EXIT. It runs when the script ends for any reason: normal end, exit, an error under set -e, or Ctrl+C:
#!/usr/bin/env bash
set -euo pipefail
workdir="$(mktemp -d)"
cleanup() {
local rc=$?
rm -rf -- "$workdir"
(( rc == 0 )) || echo "finished with status $rc" >&2
exit "$rc"
}
trap cleanup EXIT
curl -fsS -o "$workdir/app.tar.gz" https://example.net/app.tar.gz
tar -xzf "$workdir/app.tar.gz" -C "$workdir"
sudo rsync -a "$workdir/app/" /srv/app/Saving $? as the first line of the handler keeps the original exit code. mktemp -d creates a private directory with a random name, safer than a fixed path in /tmp. Only one handler per signal is active, so collect all cleanup steps in one function.
How do I report which line failed?
An ERR trap fires whenever a command fails in a place where set -e would act. Combined with set -E (errtrace), it also fires inside functions:
set -Eeuo pipefail
on_error() {
local rc=$? line=$1
echo "error $rc at line $line: $BASH_COMMAND" >&2
logger -t "${0##*/}" "failed at line $line (status $rc)"
}
trap 'on_error $LINENO' ERRBASH_COMMAND holds the command that failed, and logger copies the message to the journal, readable later with journalctl -t scriptname. Use single quotes around the trap string so $LINENO is expanded when the error happens, not when the trap is set. This one block turns a silent stop into a clear message that points at the exact line.
How do I handle Ctrl+C and termination signals?
Trap INT and TERM to stop gracefully, for example to finish the current file or release a lock. systemd sends TERM when it stops a service:
stop_requested=0
trap 'stop_requested=1' INT TERM
for f in /srv/queue/*.job; do
(( stop_requested )) && { echo "stopping early"; break; }
process_job "$f"
doneThe loop finishes the job it is working on and then exits instead of dying halfway. The EXIT trap still runs afterwards. trap - INT TERM resets the default behaviour, and trap -p lists what is set. If you run scripts as services, the systemd services guide explains stop timeouts.
How do I retry a flaky step and prevent overlapping runs?
Wrap network calls in a retry function with a growing pause, and use flock so a scheduled script never runs twice at once:
retry() {
local tries=$1 delay=2 n=1; shift
until "$@"; do
(( n++ >= tries )) && return 1
echo "retry $n/$tries in ${delay}s: $*" >&2
sleep "$delay"; delay=$(( delay * 2 ))
done
}
exec 9> /run/lock/sync-job.lock
flock -n 9 || { echo "already running" >&2; exit 0; }
retry 5 rsync -a /srv/data/ deploy@198.51.100.24:/srv/data/flock -n fails immediately when another copy holds the lock, and the lock disappears automatically when the script exits, even after a crash. /run/lock needs root on some systems; a normal user can use a path in their home folder. Use this pair for anything started by cron or a systemd timer.
Which exit codes should my script return?
Return 0 for success, 1 for general failure and 2 for wrong usage, and document any other code you use, so callers and monitoring can tell problems apart:
usage() { echo "usage: ${0##*/} SOURCE DEST" >&2; exit 2; }
(( $# == 2 )) || usage
[[ -d "$1" ]] || { echo "no such folder: $1" >&2; exit 3; }
./sync.sh /srv/data /backup; echo "exit code: $?"Codes above 125 have special meanings (126 not executable, 127 not found, 128 plus a signal number for a killed process), so keep your own below that. Print error messages to standard error, never to standard output, so piped output stays clean. Finally, check every script with shellcheck; it flags many cases where set -e does not protect you, as described in Write and run a Bash script.
Questions about Error handling with set -euo pipefail
Should every script start with set -euo pipefail?
For admin and deploy scripts, yes, it is a good default. Treat it as a safety net, not a replacement for explicit checks on the steps that matter.
Why did my script exit silently with set -e?
A command returned non-zero, often grep finding nothing or (( count++ )) when count was 0. Add an ERR trap to print the line, then allow the case with || true.
Does set -e work inside command substitution?
Subshells from $( ) do not inherit errexit by default. Set shopt -s inherit_errexit (Bash 4.4 and later) to change that.
Can I turn the options off for one section?
Yes. set +e disables errexit until set -e turns it back on; the same works for +u and +o pipefail.
Does the EXIT trap run when the server reboots?
Only if the script receives a signal it can handle, such as TERM during an orderly shutdown. A hard power loss or SIGKILL gives no chance to run any trap.