Skip to main content

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
bash --version | head -n 1

It 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
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. false fails, so not reached never prints and you see exit code 1.
  • -u (nounset) treats an unset variable as an error. $USER_NAME was never set, so Bash prints USER_NAME: unbound variable and exits with a non-zero code instead of greeting nobody.
  • Without pipefail, a pipe's status is the status of its last command. grep fails on the missing file, sort succeeds on empty input, and the script carries on.
  • With -o pipefail, the pipe fails if any command in it fails, so the last line prints exit code 2, the code grep returned.

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:

Bash
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.sh

The script reaches its last line and exits with 0, even though three commands failed:

  1. Conditions switch errexit off for everything inside them. Because copy_config is called from an if, -e is ignored for the whole function, not only its last command. The same applies after while, until, &&, || and !.
  2. Command substitution does not inherit -e. Inside $( ), the false fails and the echo after it still runs, so the substitution succeeds.
  3. 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:

Bash
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:

Bash
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"; fi

The 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:

Bash
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"; done

Unquoted, 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:

Bash
cd ~/safe-bash-demo/photos
files=(*.jpg)
echo "found ${#files[@]} files"
for f in "${files[@]}"; do echo "file: $f"; done

If 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:

Bash
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 nullglob

IFS 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:

Bash
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:

Bash
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; fi

It 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:

Bash
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:

Bash
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:

Bash
cd ~/safe-bash-demo
if [[ -e "$(cat last-workdir.txt)" ]]; then echo "temp folder left behind"; false; else echo "temp folder is gone"; fi

It 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.

Bash
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 $?, $LINENO and $BASH_COMMAND expand when the trap fires, not when you set it. $? comes first, before any other command can replace it.
  • -E (errtrace) makes functions inherit the ERR trap. Without it, a failure inside check_folders would not trigger the trap.
  • The ERR trap follows the same rules as errexit: it stays quiet inside if, && 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:

Bash
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.txt

The 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
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:

  • local limits a variable to its function. Declare it on its own line before you assign a command substitution, because local out=$(cmd) returns the status of local, which is always 0.
  • readonly fixes a value for the rest of the script, so a later line cannot change a setting by accident.
Bash
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:

Bash
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:

Bash
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 scratch

The -- 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:

Bash
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; fi

Step 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.

Bash
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.sh

The choices worth noticing:

  • stage is a global, set to empty at the top. The EXIT trap runs after main has returned, when any local variable 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, so app-<version>.tar.gz appears complete or not at all. A folder from plain mktemp -d would be in /tmp, often a different filesystem, where mv copies byte by byte.
  • Checks that should fail with a clear message use || die. The || keeps errexit and the ERR trap out of the way, and die explains in words. Anything unexpected falls through to the ERR trap 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 puts 1.10.0 after 1.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:

Bash
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 releases

Check it worked

The archive and its checksum are in releases, the checksum matches and the archive contains the VERSION file:

Bash
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/VERSION

ls 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:

Bash
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:

Bash
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:

Bash
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 releases

The 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:

Bash
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 releases

You 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

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.