Error handling and debugging
By default, Bash keeps going after a command fails. In a script that does cd build and then rm -rf *, a failed cd means deleting the wrong folder. This lesson covers how to make scripts stop on errors, clean up after themselves, and how to find out what went wrong.
The problem
#!/usr/bin/env bash
cd /no/such/folder
echo "now deleting everything in $(pwd)…"
echo "(imagine rm -rf * here)"bash careless.sh
echo "exit code: $?"careless.sh: line 2: cd: /no/such/folder: No such file or directory now deleting everything in /home/you… (imagine rm -rf * here) exit code: 0
The cd failed, the script carried on in the wrong folder, and it even finished with exit code 0, so CI or cron would think everything was fine.
Strict mode: set -euo pipefail
Put this line at the top of almost every script:
set -euo pipefail| Option | Effect |
|---|---|
-e (errexit) |
Exit as soon as a command fails |
-u (nounset) |
Treat unset variables as an error (catches typos) |
-o pipefail |
A pipeline fails if any command in it fails, not just the last |
#!/usr/bin/env bash
set -euo pipefail
cd /no/such/folder
echo "this line never runs"bash strict.sh
echo "exit code: $?"strict.sh: line 3: cd: /no/such/folder: No such file or directory exit code: 1
-u catches typos
#!/usr/bin/env bash
set -euo pipefail
build_dir="dist"
echo "cleaning $biuld_dir"bash typo.sh
echo "exit code: $?"typo.sh: line 4: biuld_dir: unbound variable exit code: 1
Without -u that would have printed cleaning and, in a real script, run rm -rf "$biuld_dir"/*, which means rm -rf /*. Use ${var:-} when a variable is allowed to be empty: if [[ -n ${DEBUG:-} ]].
pipefail catches hidden failures
grep "x" /no/such/file | sort
echo "without pipefail: $?"
set -o pipefail
grep "x" /no/such/file | sort
echo "with pipefail: $?"grep: /no/such/file: No such file or directory without pipefail: 0 grep: /no/such/file: No such file or directory with pipefail: 2
Without pipefail, the pipeline's exit code is sort's, which succeeded.
Where -e doesn't stop
set -e deliberately ignores failures that are being tested: in if conditions, before && or ||, and after !. That's what lets you handle errors yourself:
#!/usr/bin/env bash
set -euo pipefail
if ! grep -q "admin" /etc/passwd; then
echo "no admin user (handled, script continues)"
fi
mkdir /proc/cant-do-this 2>/dev/null || echo "mkdir failed (handled)"
count=$(grep -c "nologin" /etc/passwd || true)
echo "nologin accounts: $count"
echo "finished normally"bash handled.shno admin user (handled, script continues) mkdir failed (handled) nologin accounts: 17 finished normally
|| true says "a failure here is fine". grep exits with 1 when it finds nothing, which would otherwise stop a strict script.
Your own error messages
Combine checks with a die helper so failures are clear:
#!/usr/bin/env bash
set -euo pipefail
die() { echo "error: $*" >&2; exit 1; }
[[ $# -eq 1 ]] || die "usage: install.sh VERSION"
[[ $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "'$1' is not a version like 1.2.3"
prefix=${PREFIX:-/usr/local/bin}
command -v curl > /dev/null || die "curl is not installed"
[[ -d $prefix && -w $prefix ]] || die "can't write to $prefix (try sudo, or set PREFIX)"
echo "installing version $1 into $prefix"bash install.sh; echo "exit $?"
bash install.sh latest; echo "exit $?"
bash install.sh 2.1.0; echo "exit $?"
mkdir -p ~/bin && PREFIX=~/bin bash install.sh 2.1.0; echo "exit $?"error: usage: install.sh VERSION exit 1 error: 'latest' is not a version like 1.2.3 exit 1 error: can't write to /usr/local/bin (try sudo, or set PREFIX) exit 1 installing version 2.1.0 into /home/you/bin exit 0
Check everything you can before changing anything. A script that fails halfway is much harder to recover from than one that refuses to start.
Cleaning up with trap
trap runs a command when the script exits, however it exits: success, failure, or Ctrl + C. Use it to delete temporary files and release locks:
#!/usr/bin/env bash
set -euo pipefail
tmp=$(mktemp -d)
cleanup() {
rm -rf "$tmp"
echo "cleaned up $tmp" >&2
}
trap cleanup EXIT
echo "working in a temp folder"
echo "data" > "$tmp/part1"
false # something fails here…
echo "never reached"bash work.sh 2>&1 | sed 's|/tmp/tmp\.[A-Za-z0-9]*|/tmp/tmp.XXXX|'
echo "exit code: ${PIPESTATUS[0]}"working in a temp folder cleaned up /tmp/tmp.XXXX exit code: 1
(The sed hides the random temp-folder name.)
mktemp/mktemp -dcreate a unique temporary file or folder. Never hard-code/tmp/myfile: two copies of the script would collide.trap cleanup EXITrunscleanupwhenever the script ends.trap 'echo interrupted' INTreacts to Ctrl + C;TERMtokill.
Reporting where it failed
The ERR trap runs when a command fails, and $LINENO and $BASH_COMMAND tell you where:
#!/usr/bin/env bash
set -euo pipefail
trap 'echo "failed at line $LINENO: $BASH_COMMAND (exit $?)" >&2' ERR
echo "step 1"
ls /etc/hostname > /dev/null
echo "step 2"
cp /no/such/file /tmp/
echo "step 3"bash where.shstep 1 step 2 cp: cannot stat '/no/such/file': No such file or directory failed at line 7: cp /no/such/file /tmp/ (exit 1)
Retrying flaky commands
Networks fail. Retry with a growing pause instead of giving up at once:
#!/usr/bin/env bash
set -euo pipefail
retry() {
local max=$1 delay=1 attempt=1
shift
until "$@"; do
if (( attempt >= max )); then
echo "giving up after $attempt attempts: $*" >&2
return 1
fi
echo "attempt $attempt failed, retrying in ${delay}s…" >&2
sleep "$delay"
(( attempt++ ))
(( delay *= 2 ))
done
}
flaky() { [[ -f third-time ]] || { [[ -f second-time ]] && touch third-time; touch second-time; return 1; }; }
retry 5 flaky && echo "succeeded"
retry 2 false || echo "retry reported failure"bash retry.shattempt 1 failed, retrying in 1s… attempt 2 failed, retrying in 2s… succeeded attempt 1 failed, retrying in 1s… giving up after 2 attempts: false retry reported failure
"$@" runs whatever command was passed in, with its arguments intact. A real use: retry 5 curl -fsS https://api.example.com/health.
Debugging
set -x: trace every command
#!/usr/bin/env bash
total=0
for n in 1 2 3; do
total=$((total + n))
done
name="world"
echo "Hello $name, total $total"bash -x buggy.sh+ total=0 + for n in 1 2 3 + total=1 + for n in 1 2 3 + total=3 + for n in 1 2 3 + total=6 + name=world + echo 'Hello world, total 6' Hello world, total 6
Each line starting with + is a command after expansion, so you see the real values. Run a whole script with bash -x script.sh, or switch tracing on and off around the suspicious part with set -x … set +x.
Make the trace more useful by showing file and line numbers:
export PS4='+ ${BASH_SOURCE##*/}:${LINENO}: '
bash -x buggy.sh 2>&1 | head -4+ buggy.sh:2: total=0 + buggy.sh:3: for n in 1 2 3 + buggy.sh:4: total=1 + buggy.sh:3: for n in 1 2 3
Other debugging tools
| Tool | Use |
|---|---|
bash -n script.sh |
Check the syntax without running anything |
shellcheck script.sh |
Find bugs and bad practices (use it always) |
echo "DEBUG: var=[$var]" >&2 |
The old reliable. Brackets make empty values and spaces visible |
declare -p var |
Show a variable exactly, including arrays |
printf 'if true; then\n echo hi\n' > broken.sh
bash -n broken.sh
arr=(a "b c")
declare -p arrbroken.sh: line 3: syntax error: unexpected end of file declare -a arr=([0]="a" [1]="b c")
Practice
- Add
set -euo pipefailto an earlier script and see which hidden bugs it reveals. - Write a script that creates a temporary folder, downloads (or creates) a file into it, and always deletes the folder with
trap, even when you press Ctrl + C. - Use the
retryfunction to wait until a filereadyexists, checking 5 times. - Run one of your scripts with
bash -xand find a line where a variable had a value you didn't expect.
1.What does set -e do?
2.grep -c foo file finds nothing in a set -e script. What happens?
3.What is trap cleanup EXIT for?
4.Which option makes a pipeline fail if any command in it fails?