Linux and servers · Intermediate · 18 min
Write safer Bash scripts with strict mode and traps
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · GNU Bash 5.3 (bash 5.3-2ubuntu1)
You will build a small Bash release script that stops on the first error, says which line failed, survives file names with spaces and always removes its temporary files.
On this page
Bash runs a script line by line and, by default, carries on after a command fails. A failed cd followed by rm -rf * deletes files in the wrong folder. A typo in a variable name expands to nothing. A broken download piped into tar looks like success because only the last command in a pipe counts. Strict mode and traps change those defaults, but they have gaps that catch experienced people too.
In this tutorial you work in ~/safe-bash-demo. You turn on strict mode and watch each option fire, find the places where it stays silent, handle file names with spaces, clean up temporary folders on every kind of exit, and print the failing line when something breaks. Last, you put it all into release.sh, a script that packages a folder as a versioned archive with a checksum, fails loudly and never leaves half-finished work behind.
Everything here uses Bash 5.3, which Ubuntu 26.04 ships as /bin/bash. Check yours:
bash --version | head -n 1It prints something like GNU bash, version 5.3.0(1)-release (x86_64-pc-linux-gnu). Any Bash from 4.4 onwards has every feature used here.
Step 1 · Watch each strict-mode option fire
The usual first line of a careful script is set -euo pipefail. It is three separate options. Try each on its own with bash -c, which runs a short script in a new shell, so your own terminal is not affected:
bash -c 'set -e; false; echo "not reached"' || echo "exit code $?"
bash -c 'set -u; echo "Hello, $USER_NAME"' || echo "exit code $?"
bash -c 'set -e; grep root /etc/no-such-file | sort; echo "the pipe hid the failure"'
bash -c 'set -eo pipefail; grep root /etc/no-such-file | sort; echo "not reached"' || echo "exit code $?"What each line shows:
-e(errexit) stops the script when a command fails.falsefails, sonot reachednever prints and you seeexit code 1.-u(nounset) treats an unset variable as an error.$USER_NAMEwas never set, so Bash printsUSER_NAME: unbound variableand exits with a non-zero code instead of greeting nobody.- Without
pipefail, a pipe's status is the status of its last command.grepfails on the missing file,sortsucceeds on empty input, and the script carries on. - With
-o pipefail, the pipe fails if any command in it fails, so the last line printsexit code 2, the codegrepreturned.
Check it worked
You see exit code 1, then the unbound variable message and its exit code, then the pipe hid the failure, and last exit code 2. The word not reached appears nowhere in the output.
Step 2 · Find where errexit stays silent
set -e is not "stop on any failure". Bash ignores it in several places, and knowing them matters more than turning it on. Write a script that runs into three of them:
mkdir -p ~/safe-bash-demo
cd ~/safe-bash-demo
cat > gaps.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
copy_config() {
cp /etc/no-such-file.conf /tmp/
echo "gap 1: copy_config kept going after cp failed"
}
if copy_config; then
echo "gap 1: the if saw success"
fi
result=$(false; echo "finished")
echo "gap 2: the substitution returned '$result'"
echo "gap 3: $(false) the outer echo hid the failure"
echo "end of script"
EOF
chmod +x gaps.sh
./gaps.shThe script reaches its last line and exits with 0, even though three commands failed:
- Conditions switch errexit off for everything inside them. Because
copy_configis called from anif,-eis ignored for the whole function, not only its last command. The same applies afterwhile,until,&&,||and!. - Command substitution does not inherit
-e. Inside$( ), thefalsefails and theechoafter it still runs, so the substitution succeeds. - A failing substitution inside another command is hidden. The status that counts is the outer
echo's.
Two more traps of the same kind: ((count++)) returns status 1 when count was 0, which stops a strict script by surprise (write count=$((count + 1)) instead), and a line such as ! grep -q error app.log on its own never stops the script, whatever grep returns.
Now write the fixed version. shopt -s inherit_errexit makes command substitutions honour -e, and the function returns its failure on purpose instead of relying on errexit:
cd ~/safe-bash-demo
cat > fixed.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
shopt -s inherit_errexit
copy_config() {
cp /etc/no-such-file.conf /tmp/ || return
echo "copy done"
}
if ! copy_config; then
echo "copy_config failed, and the script knows it" >&2
fi
result=$(false; echo "finished")
echo "not reached: $result"
EOF
chmod +x fixed.sh
./fixed.sh || echo "exit code $?"return with no number passes on the status of the last command, here cp's 1.
Check it worked
Count the lines where the first script got away with a failure, then confirm the fixed one stops before its last line:
cd ~/safe-bash-demo
./gaps.sh 2>/dev/null | grep -c '^gap'
if ./fixed.sh 2>/dev/null | grep -q 'not reached'; then echo "inherit_errexit is not on"; false; else echo "fixed.sh stopped at the failing substitution"; fiThe first command prints 4. The second prints fixed.sh stopped at the failing substitution.
Step 3 · Quote variables and keep file names in arrays
Strict mode does nothing about word splitting. When you write $file without quotes, Bash splits the value on spaces, tabs and newlines and then expands any * in it. Make two files and see what happens:
mkdir -p ~/safe-bash-demo/photos
cd ~/safe-bash-demo/photos
touch "beach day.jpg" market.jpg
file="beach day.jpg"
ls $file || echo "unquoted: ls was given two names"
ls "$file"
for f in $(ls); do echo "word: $f"; doneUnquoted, ls looks for beach and day.jpg and fails on both. Quoted, it finds the file. The $(ls) loop splits two file names into three words. The rule is short: put double quotes around every expansion ("$file", "$(command)", "${files[@]}") unless you want splitting and can say why.
To hold a list of file names, use an array filled by a glob, never the output of ls:
cd ~/safe-bash-demo/photos
files=(*.jpg)
echo "found ${#files[@]} files"
for f in "${files[@]}"; do echo "file: $f"; doneIf a glob matches nothing, Bash keeps it as the literal text *.png, so a loop runs once on a file that does not exist. shopt -s nullglob makes an unmatched glob expand to nothing instead:
cd ~/safe-bash-demo/photos
pngs=(*.png)
echo "without nullglob: ${#pngs[@]} item, '${pngs[0]}'"
shopt -s nullglob
pngs=(*.png)
echo "with nullglob: ${#pngs[@]} items"
shopt -u nullglobIFS is the list of characters Bash splits on. Change it for one command only, by putting it in front of that command, rather than for the whole script:
line="beach day.jpg,2048,2026-11-02"
IFS=, read -r name size taken <<< "$line"
echo "name=$name size=$size taken=$taken"IFS=, applies to this read alone, and -r stops backslashes in the input being treated as escapes. To read a file line by line without trimming spaces, the same idea becomes while IFS= read -r line; do ...; done < file.txt.
Check it worked
The array holds both photos, with the space kept inside the first name:
cd ~/safe-bash-demo/photos
files=(*.jpg)
if [[ ${#files[@]} -eq 2 && ${files[0]} == "beach day.jpg" ]]; then echo "array holds 2 files: ${files[*]}"; else echo "unexpected: ${#files[@]} items"; false; fiIt prints array holds 2 files: beach day.jpg market.jpg. The read line earlier printed name=beach day.jpg size=2048 taken=2026-11-02.
Step 4 · Clean up temporary files on every exit
Scripts that stage work in a temporary folder must remove it whether they succeed, fail or are interrupted. mktemp -d makes a folder with a unique name that only you can read, and a trap on EXIT runs your cleanup however the script ends:
cd ~/safe-bash-demo
cat > cleanup.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
shopt -s inherit_errexit
workdir=$(mktemp -d)
cleanup() {
rm -rf -- "$workdir"
echo "cleaned up $workdir" >&2
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
echo "$workdir" > last-workdir.txt
date > "$workdir/stamp.txt"
if [[ ${1:-} == slow ]]; then
sleep 30
fi
cp "$workdir/stamp.txt" /no-such-folder/
echo "not reached"
EOF
chmod +x cleanup.sh
./cleanup.sh || echo "exit code $?"cp fails, errexit stops the script, and the EXIT trap still runs: you see the cp error, then cleaned up /tmp/tmp. followed by a random suffix, then exit code 1. The trap keeps the script's exit code.
The three signal traps turn a hang-up (HUP), Ctrl+C (INT) and a polite kill (TERM) into a normal exit, which runs the EXIT trap on the way out. The numbers follow the shell convention of 128 plus the signal number. HUP is the one that bites over unreliable links: if your SSH session drops while a script runs in it, as can happen on a mobile or prepaid data connection, the script gets SIGHUP and still tidies up. Nothing can trap kill -9, so no script cleans up after that.
Now interrupt the slow version. timeout sends TERM after 2 seconds:
cd ~/safe-bash-demo
timeout 2 ./cleanup.sh slow || echo "exit code $?"After two seconds you see cleaned up ... and exit code 124, which is timeout's way of saying it stopped the command.
Check it worked
The folder named in last-workdir.txt is gone:
cd ~/safe-bash-demo
if [[ -e "$(cat last-workdir.txt)" ]]; then echo "temp folder left behind"; false; else echo "temp folder is gone"; fiIt prints temp folder is gone. Running ls -d /tmp/tmp.* shows no folder from either run.
Step 5 · Report the failing line with an ERR trap
When a strict script stops, the only clue by default is the failing command's own error message, which often says nothing about where in the script you were. A trap on ERR runs whenever a command fails in a place where errexit would act, and two variables tell it what happened: LINENO, the current line, and BASH_COMMAND, the command that was running.
cd ~/safe-bash-demo
cat > report.sh <<'EOF'
#!/usr/bin/env bash
set -Eeuo pipefail
shopt -s inherit_errexit
on_error() {
echo "error: line $2: '$3' exited with status $1" >&2
}
trap 'on_error "$?" "$LINENO" "$BASH_COMMAND"' ERR
check_folders() {
ls / > /dev/null
ls /no-such-folder
}
echo "checking folders"
check_folders
echo "not reached"
EOF
chmod +x report.sh
./report.sh || echo "exit code $?"Three details make this work:
- The trap text is in single quotes, so
$?,$LINENOand$BASH_COMMANDexpand when the trap fires, not when you set it.$?comes first, before any other command can replace it. -E(errtrace) makes functions inherit theERRtrap. Without it, a failure insidecheck_folderswould not trigger the trap.- The
ERRtrap follows the same rules as errexit: it stays quiet insideif,&&and||, which is what you want for failures you handle yourself.
Check it worked
The message names line 12, the ls inside the function, rather than line 16 where the function was called:
cd ~/safe-bash-demo
./report.sh 2> report-errors.txt || echo "exit code $?"
cat report-errors.txt
grep -q "error: line 12: 'ls /no-such-folder' exited with status 2" report-errors.txtThe file holds the ls error followed by error: line 12: 'ls /no-such-folder' exited with status 2, and the script exits with 2, the status ls returned.
Step 6 · Guard destructive commands and scope your variables
The most expensive Bash bug is a delete whose path came out empty. rm -rf "$dir"/* with an empty $dir becomes rm -rf /*. Strict mode's -u only catches a variable that was never set, not one set to an empty string. ${dir:?} catches both: it stops with an error if dir is unset or empty.
The next command only prints the rm line, so it is safe to run, and the guard stops it before even that:
bash -c 'dir=""; echo rm -rf "${dir:?}"/*' || echo "stopped: exit code $?"Bash prints dir: parameter null or not set and echo never runs. Put :? on every variable that forms part of a path you delete, and add a message after it to explain: ${1:?usage: prune.sh <folder>}.
Two more habits keep variables from leaking or changing under you:
locallimits a variable to its function. Declare it on its own line before you assign a command substitution, becauselocal out=$(cmd)returns the status oflocal, which is always 0.readonlyfixes a value for the rest of the script, so a later line cannot change a setting by accident.
bash -c 'set -e; f() { local out=$(false); echo "local hid the failure"; }; f'
bash -c 'set -e; f() { local out; out=$(false); echo "not reached"; }; f' || echo "exit code $?"
bash -c 'set -e; readonly keep=3; keep=5; echo "not reached"' || echo "exit code $?"The first line prints local hid the failure. The second stops with exit code 1. The third prints keep: readonly variable and stops.
Use [[ ]] for tests in Bash scripts rather than [ ]. [ is an ordinary command, so its arguments are split like any other: a value with a space turns into extra arguments. [[ ]] is part of the shell's syntax, does no word splitting inside, and adds == pattern matching and =~ regular expressions:
name="beach day"
[ $name = "beach day" ] || echo "[ ] split the name and failed"
[[ $name == "beach day" ]]
echo "[[ ]] compared the whole value"Now use all of it in a small prune script. Warning: prune.sh deletes *.tmp files in the folder you give it. Run it only on the practice folder below:
cd ~/safe-bash-demo
cat > prune.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
shopt -s inherit_errexit
readonly target_dir="${1:?usage: prune.sh <folder>}"
prune() {
local dir=$1
local count
count=$(find "$dir" -maxdepth 1 -name '*.tmp' | wc -l)
echo "removing $count .tmp files from $dir" >&2
rm -f -- "${dir:?}"/*.tmp
}
if [[ ! -d $target_dir ]]; then
echo "not a folder: $target_dir" >&2
exit 2
fi
prune "$target_dir"
EOF
chmod +x prune.sh
mkdir -p scratch
touch scratch/a.tmp "scratch/b c.tmp" scratch/keep.txt
./prune.sh || echo "exit code $?"
./prune.sh "no such folder" || echo "exit code $?"
./prune.sh scratchThe -- after rm -f ends the options, so a file whose name starts with a dash is treated as a name, not a flag.
Check it worked
The first run prints something like ./prune.sh: line 5: 1: usage: prune.sh <folder>, the second not a folder: no such folder with exit code 2, the third removing 2 .tmp files from scratch. Only keep.txt is left:
cd ~/safe-bash-demo
ls scratch
if [[ $(ls scratch) == keep.txt ]]; then echo "only keep.txt is left"; else echo "unexpected files in scratch"; false; fiStep 7 · Write the release script
release.sh takes a source folder, a version and a releases folder. It copies the source into a staging folder, adds a VERSION file, builds app-<version>.tar.gz with a SHA-256 checksum next to it, moves both into place and keeps the three newest releases. Messages go to stderr with a UTC timestamp, so stdout stays free for anything another program might read, and a log file can collect the messages on their own.
cd ~/safe-bash-demo
cat > release.sh <<'EOF'
#!/usr/bin/env bash
# release.sh: package a folder as app-<version>.tar.gz with a SHA-256 checksum.
# Usage: release.sh <source-dir> <version> <releases-dir>
set -Eeuo pipefail
shopt -s inherit_errexit
readonly script_name=${0##*/}
readonly keep_releases=3
stage=""
log() { printf '%s %s: %s\n' "$(date -u +%FT%TZ)" "$script_name" "$*" >&2; }
die() { log "error: $*"; exit 1; }
on_error() { log "error: line $2: '$3' exited with status $1"; }
cleanup() {
if [[ -n $stage ]]; then
rm -rf -- "$stage"
fi
}
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'on_error "$?" "$LINENO" "$BASH_COMMAND"' ERR
prune_old() {
local dir=$1 keep=$2
local -a releases
mapfile -t releases < <(find "$dir" -maxdepth 1 -name 'app-*.tar.gz' | sort -V)
local count=${#releases[@]}
if (( count <= keep )); then
return 0
fi
local old
for old in "${releases[@]:0:count-keep}"; do
log "removing old release ${old##*/}"
rm -f -- "${old:?}" "${old:?}.sha256"
done
}
main() {
if [[ $# -ne 3 ]]; then
echo "usage: $script_name <source-dir> <version> <releases-dir>" >&2
exit 2
fi
local src=$1 version=$2 out=$3
[[ -d $src ]] || die "source folder not found: $src"
[[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "version must look like 1.2.3, not: $version"
local name="app-$version"
[[ ! -e "$out/$name.tar.gz" ]] || die "release already exists: $out/$name.tar.gz"
mkdir -p -- "$out"
stage=$(mktemp -d "$out/.stage.XXXXXX")
log "staging $src as $name"
mkdir -- "$stage/$name"
cp -R -- "$src"/. "$stage/$name"/
printf '%s\n' "$version" > "$stage/$name/VERSION"
tar -C "$stage" -czf "$stage/$name.tar.gz" "$name"
(cd -- "$stage" && sha256sum "$name.tar.gz" > "$name.tar.gz.sha256")
mv -- "$stage/$name.tar.gz.sha256" "$out"/
mv -- "$stage/$name.tar.gz" "$out"/
log "released $out/$name.tar.gz"
prune_old "$out" "$keep_releases"
}
main "$@"
EOF
chmod +x release.shThe choices worth noticing:
stageis a global, set to empty at the top. TheEXITtrap runs aftermainhas returned, when anylocalvariable is gone. A trap that used a local would find nothing to delete, or stop on-u.- The staging folder sits inside the releases folder (a hidden
.stage.folder). Moving a file within one filesystem is a rename, soapp-<version>.tar.gzappears complete or not at all. A folder from plainmktemp -dwould be in/tmp, often a different filesystem, wheremvcopies byte by byte. - Checks that should fail with a clear message use
|| die. The||keeps errexit and theERRtrap out of the way, anddieexplains in words. Anything unexpected falls through to theERRtrap with a line number. - Versions are validated before use. The
=~test means a version can never contain a space, a slash or.., so it is safe inside file names. - Old releases are sorted with
sort -V, which puts1.10.0after1.2.0. A plain glob sorts as text and would delete the wrong one.
Create a small app to release, then run the script once:
mkdir -p ~/safe-bash-demo/app
printf '<h1>Hello from the app</h1>\n' > ~/safe-bash-demo/app/index.html
cd ~/safe-bash-demo
./release.sh app 1.0.0 releasesCheck it worked
The archive and its checksum are in releases, the checksum matches and the archive contains the VERSION file:
cd ~/safe-bash-demo
ls releases
(cd releases && sha256sum -c app-1.0.0.tar.gz.sha256)
tar -xOzf releases/app-1.0.0.tar.gz app-1.0.0/VERSIONls shows app-1.0.0.tar.gz and app-1.0.0.tar.gz.sha256, sha256sum prints app-1.0.0.tar.gz: OK, and the last command prints 1.0.0.
Step 8 · Prove it fails loudly and cleans up
A safety feature you have not seen fail is a guess. Try the cases the script is meant to refuse:
cd ~/safe-bash-demo
./release.sh app 1.0.0 releases || echo "exit code $?"
./release.sh app one releases || echo "exit code $?"
./release.sh missing 1.0.1 releases || echo "exit code $?"
./release.sh app || echo "exit code $?"Each prints a timestamped error: line (or the usage line) and a non-zero exit code: 1 for the three refusals, 2 for the wrong number of arguments.
Now make a command fail halfway through, after the staging folder exists. A common way to test this is to put a stand-in for one command first on PATH. This fake tar prints an error and exits with 2:
cd ~/safe-bash-demo
mkdir -p fakebin
printf '#!/bin/sh\necho "tar: simulated failure" >&2\nexit 2\n' > fakebin/tar
chmod +x fakebin/tar
PATH="$PWD/fakebin:$PATH" ./release.sh app 1.1.0 releases || echo "exit code $?"You see staging app as app-1.1.0, the fake tar message, then error: line followed by the line number of the tar command, and exit code 2.
Last, check that old releases are pruned in version order. Send the messages to a log file this time:
cd ~/safe-bash-demo
for v in 1.0.1 1.2.0 1.10.0; do ./release.sh app "$v" releases 2>> release.log; done
cat release.log
ls releasesThe log ends with removing old release app-1.0.0.tar.gz, and releases holds 1.0.1, 1.2.0 and 1.10.0 with their checksums.
Check it worked
No staging folder survived the failed run, no 1.1.0 archive was left half-written, and the oldest release is the one that went:
cd ~/safe-bash-demo
if compgen -G 'releases/.stage.*' > /dev/null; then echo "a staging folder was left behind"; false; else echo "no staging folders left"; fi
if [[ -e releases/app-1.1.0.tar.gz || -e releases/app-1.0.0.tar.gz ]]; then echo "unexpected release files"; false; else echo "1.1.0 never landed and 1.0.0 was pruned"; fi
[[ -e releases/app-1.10.0.tar.gz ]]
ls -A releasesYou see no staging folders left and 1.1.0 never landed and 1.0.0 was pruned, and ls -A lists six files, with no hidden folders. When you have finished, remove the practice folder with rm -rf ~/safe-bash-demo.
Next steps
- Run ShellCheck over
release.shto catch the quoting and errexit mistakes this tutorial describes, automatically, in Find bugs in shell scripts with ShellCheck. - Replace the positional arguments with proper
-vand-ooptions in Parse options and validate input in Bash scripts with getopts. - Run a strict script on a timetable, with its stderr going to a log, in Schedule jobs with cron.
- If any of the basics felt new, go back to Hello World in Bash.
Related tutorials
- Write least-privilege sudo rules with visudoYou will replace blanket sudo access with checked rule files in /etc/sudoers.d that let two operators restart one service and edit one file, give an automation account a password-free command list, and audit what every account can run.
- Upgrade a server from Ubuntu 24.04 LTS to 26.04 LTSYou will take a backed-up Ubuntu 24.04 server through do-release-upgrade to 26.04 LTS over SSH with a fallback login, then confirm services, repositories and language runtimes work on the new release.
- Find your way around the Linux filesystem: /etc, /var, /usr and the restYou will know what each top-level folder on an Ubuntu 26.04 server is for, find where any file came from with dpkg, which, file and findmnt, and have a map of where Nginx keeps its binary, config, data, logs and unit file.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials