bash
Writing Bash scripts that survive production
Strict mode, traps, locks, idempotent steps and shellcheck, plus the places where set -e quietly doesn't do what you think.
6 min read
Bash is the language a lot of us write the most and trust the least. Almost every deploy pipeline has a shell script somewhere in the middle of it, usually written in a hurry, never tested, and fine right up until the day a variable comes back empty.
Here's a template worth starting from. The rest of the post is why each line is there.
#!/usr/bin/env bash
set -Eeuo pipefail
readonly SCRIPT_NAME=${0##*/}
log() { printf '%s [%s] %s\n' "$(date -u +%FT%TZ)" "$SCRIPT_NAME" "$*" >&2; }
die() { log "ERROR: $*"; exit 1; }
tmp_dir=$(mktemp -d)
cleanup() { rm -rf "$tmp_dir"; }
trap cleanup EXIT
trap 'log "failed at line $LINENO: $BASH_COMMAND"' ERR
: "${DEPLOY_ENV:?DEPLOY_ENV must be set}"
main() {
log "deploying to $DEPLOY_ENV"
# ...
}
main "$@"What set -Eeuo pipefail actually does
-e exits as soon as a command fails. You knew that one.
-u turns a reference to an unset variable into an error instead of an empty string, which catches typos and missing environment variables. It doesn't catch a variable that's set but empty, though, and that's the one that hurts most next to rm. In 2015 Valve's Steam client for Linux shipped a script containing rm -rf "$STEAMROOT/"*. When STEAMROOT came back empty, that became rm -rf /*, and some users lost every file they owned. For any path you're about to delete, write "${STEAMROOT:?}/"* instead: the :? makes the expansion fail when the variable is unset or empty. ShellCheck flags the unguarded version (it's rule SC2115, and the rule's own example is that exact Steam line).
-o pipefail makes a pipeline fail when any command in it fails, not only the last one. Without it this "succeeds" even when the dump dies halfway through, because gzip exited cleanly:
pg_dump app_db | gzip > backup.sql.gzThat's how you end up with a nightly backup job that's been writing truncated files for a month and reporting success the whole time.
-E makes the ERR trap fire inside functions and subshells too. Without it the trap only catches failures at the top level, which in a script built around main is almost nothing.
The two traps work together. ERR tells you where it died ($LINENO and $BASH_COMMAND are expanded when the trap fires, which is why the trap string is in single quotes). EXIT runs however the script ends, so temp files get cleaned up on success, on failure and on Ctrl-C.
Where set -e quietly does nothing
set -e has enough exceptions that some people refuse to use it. It still earns its place, but these cases are worth knowing by heart.
Anything in a condition is exempt. Commands inside if, while, or on the left of && and || can fail without stopping the script. That includes every command inside a function you call from an if:
deploy() {
cp app.conf /etc/app/ # fails...
systemctl restart app # ...and this runs anyway
}
if deploy; then
log "deployed" # and so does this
fiCall the function on its own line and check its result separately, or have it return 1 explicitly where it matters.
local eats the exit code.
f() {
local out=$(false) # $? is now the status of `local`, which is 0
echo "still running"
}Declare first, assign second: local out; out=$(false). ShellCheck warns about this one too (SC2155).
Arithmetic that evaluates to zero counts as failure.
count=0
((count++)) # the expression's value is 0, so the exit status is 1, and the script exitsThis one is maddening because it only bites on the first iteration. Write count=$((count + 1)) instead.
pipefail plus head is a race.
first=$(generate_lines | head -n 1)head exits after one line. If generate_lines is still writing, it gets SIGPIPE and exits with status 141, and pipefail turns that into a failure. Whether it happens depends on timing and on how much output there is, so it works on your laptop and fails in CI once a week. When you only want the first line, use something that reads all of its input, like sed -n 1p.
Quote everything
An unquoted variable gets split on whitespace and then glob-expanded. With file="my report.pdf", rm $file tries to delete two files called my and report.pdf. With file="*" it deletes everything in the directory.
Quote variables. Quote command substitutions. Use "${files[@]}" for arrays. It's tedious, and ShellCheck will nag about every one you miss, which is exactly what you want from it.
Make every step safe to run twice
Scripts get rerun. After a failure halfway through, by a CI retry, by a colleague who isn't sure whether it ran. Each step should do the right thing whether or not it already happened:
mkdir -p /opt/app/releases
ln -sfn "/opt/app/releases/$version" /opt/app/current
grep -qxF "$line" /etc/app/allowed_hosts || echo "$line" >> /etc/app/allowed_hosts
id -u app >/dev/null 2>&1 || useradd --system appThe -n in ln -sfn is easy to miss and it matters. Without it, if current already points at a directory, ln follows the link and creates your new symlink inside the old release instead of replacing current. Nothing errors. The deploy just doesn't happen.
Don't let two copies run at once
Cron doesn't care whether the previous run has finished. flock does:
exec 9>/var/lock/backup.lock
flock -n 9 || die "another backup is still running"The lock belongs to file descriptor 9, so it's released when the script exits, cleanly or not. No stale lock files to clean up after a crash.
Timeouts and retries
Anything that touches the network can hang. timeout from coreutils puts a ceiling on it:
timeout 30 curl -fsS https://internal.example.com/healthNote the -f on curl, by the way. Without it, curl exits 0 on a 404 or a 500, and your script carries on happily with an error page as its input.
For the flaky-but-usually-fine cases, a small retry helper:
retry() {
local attempts=$1; shift
local n=1
until "$@"; do
if (( n >= attempts )); then
return 1
fi
log "attempt $n failed, retrying: $*"
sleep $(( n * 2 ))
n=$(( n + 1 ))
done
}
retry 5 timeout 30 curl -fsS https://internal.example.com/healthThe command sits in the until condition, so a failed attempt doesn't trip set -e. That's one of the exemptions above, working in our favor for once.
Run ShellCheck in CI
shellcheck -x scripts/*.sh-x lets it follow source lines into other files. It runs in a second or two and catches most of what's in this post before any of it reaches a server. If you also want consistent formatting, shfmt -d prints a diff of what it would change.
Knowing when to stop
Bash is good at gluing commands together and bad at almost everything else. Once a script needs real data structures, parses JSON beyond a jq one-liner, or creeps past a couple of hundred lines, it's time to rewrite it in Python. That always feels like a waste of an afternoon, and it never is.
References
- The Set Builtin, GNU Bash Reference Manual:
-e,-u,-Eandpipefail, including the contexts where-eis ignored. - Bourne Shell Builtins, GNU Bash Reference Manual:
trap,ERRandEXIT. - Conditional Constructs, GNU Bash Reference Manual: the exit status of
((...)). - BashFAQ/105: Why doesn't set -e do what I expected?, Greg's Wiki.
- SC2115 and SC2155, ShellCheck wiki.
- steam-for-linux issue #3671, the public bug report for the 2015 Steam deletion.
- Man pages: flock(1), ln(1) and timeout(1).
- ShellCheck and shfmt.
#bash #linux