cd ../writing

Write boring shell scripts

A few conventions that make small Bash automation safer to rerun, easier to debug, and less surprising six months later.

On this page
  1. Fail deliberately
  2. Say where it failed
  3. Clean up on every exit
  4. Quote expansions
  5. Use arrays for argument lists
  6. Validate input up front
  7. Make reruns safe
  8. Don’t run twice at once
  9. Log decisions, not noise
  10. Let a linter read it first
  11. Know when to stop
  12. A template

Shell scripts are useful precisely because they are close to the commands you would type by hand. The trick is keeping that advantage without accumulating invisible assumptions.

“Boring” here is a compliment. A boring script does the same thing every time it runs, fails loudly and early when it cannot, can be run again after a partial failure without making things worse, and can be read by someone who did not write it. None of the conventions below are clever. That is the point.

Fail deliberately

Start by deciding what failure should mean. For many small automation scripts this is a reasonable baseline:

bash
#!/usr/bin/env bash
set -Eeuo pipefail

Each flag closes a different silent failure mode:

  • -e exits when a command fails, instead of carrying on with whatever state it left behind.
  • -u treats an unset variable as an error rather than an empty string.
  • -o pipefail makes a pipeline fail if any stage fails, not just the last. Without it, curl … | tar x succeeds whenever tar does, even if curl returned an error page.
  • -E makes an ERR trap (below) fire inside functions too.

It is not a substitute for error handling. It simply changes several silent failure modes into visible ones.

There are a few traps worth knowing, because they look correct:

bash
local out=$(fetch_config)
local out
out=$(fetch_config)

local is itself a command, and its exit status (success) replaces that of the command substitution. Declaring and assigning on separate lines keeps the failure visible.

Say where it failed

A script that dies silently on line 140 of 200 is only marginally better than one that keeps going. An ERR trap turns the failure into a message:

bash
trap 'echo "error: line $LINENO: \"$BASH_COMMAND\" exited $?" >&2' ERR

Inside the trap, $? is still the failing command’s status and $BASH_COMMAND is the command itself, so the output points straight at the problem.

Clean up on every exit

Temporary files, lock files and mounted directories should go away whether the script succeeds, fails or is interrupted. An EXIT trap runs in all three cases:

bash
workdir=$(mktemp -d)
trap 'rm -rf -- "$workdir"' EXIT

Set the trap immediately after creating the thing it cleans up, so there is no window in which the script can exit and leave it behind.

Quote expansions

Quote every expansion unless you specifically want word splitting and globbing:

cleanup.shbash
rm $target
rm -- "$target"

The unquoted version relies on the variable never containing spaces, glob characters, or a leading dash. The -- tells rm that everything after it is a filename, so a file called -rf is treated as a file.

Use arrays for argument lists

When a command’s arguments are built up conditionally, the tempting approach is a string. Strings cannot hold an argument that contains a space, and unquoting them to split them brings back every problem above. Arrays can:

sync.shbash
args=(--archive --delete --human-readable)
[[ $dry_run == 1 ]] && args+=(--dry-run)

rsync "${args[@]}" -- "$src/" "$dest/"

"${args[@]}" expands to exactly one word per element, with spaces preserved. The same rule applies to the script’s own arguments: pass them on as "$@", never $* or unquoted $@.

Validate input up front

Check arguments and preconditions before changing anything. A script that fails on its first line has done no harm; one that fails halfway through a migration has.

bash
usage() {
  echo "usage: ${0##*/} <host> <release-dir>" >&2
  exit 2
}

[[ $# -eq 2 ]] || usage
host=$1
release=$2

[[ -d $release ]] || { echo "error: $release is not a directory" >&2; exit 1; }
command -v rsync >/dev/null || { echo "error: rsync not installed" >&2; exit 1; }

Exit status 2 for usage errors is a long-standing convention, and it lets callers tell “you called me wrong” apart from “I tried and failed”.

Make reruns safe

Infrastructure work is full of partial success. A script is much easier to operate when a second run converges instead of compounding the first run’s side effects.

Check before creating, use atomic replacement where practical, and treat idempotence as an operational feature rather than a style preference. Many common commands already have an idempotent form:

Instead of Use Why
mkdir dir mkdir -p dir Succeeds if it already exists
ln -s target link ln -sfn target link Replaces an existing link instead of failing or nesting
useradd svc id svc >/dev/null 2>&1 || useradd svc Checks before creating
echo line >> file grep -qxF line file || echo line >> file Appends once, not once per run
cp then chmod install -m 0644 src dest Sets mode and ownership in one step

Files that other programs read deserve more care, because a half-written config is worse than an old one:

install-config.shbash
tmp=$(mktemp "${dest}.XXXXXX")
render_config > "$tmp"
chmod 0644 -- "$tmp"
mv -f -- "$tmp" "$dest"

Writing to a temporary file in the same directory and renaming it means readers see either the old file or the new one, never half of each. The rename is only atomic within one filesystem, which is why the temporary file goes next to the destination rather than in /tmp.

Don’t run twice at once

A cron job that takes longer than its interval will eventually overlap with itself. flock makes that a non-event:

bash
exec 9>"/run/lock/${0##*/}.lock"
flock -n 9 || { echo "already running, exiting" >&2; exit 0; }

The lock is held for as long as file descriptor 9 is open, which is the lifetime of the script, and the kernel releases it if the script is killed. There is no stale lock file to clean up.

Log decisions, not noise

A useful log line explains what the script decided to do and why. Echoing every command is sometimes helpful while debugging, but it rarely makes a good long-term interface.

Keep stdout for data and send messages to stderr, so the script can still be used in a pipeline:

bash
log() { printf '%s %s\n' "$(date -Is)" "$*" >&2; }

if [[ -e $dest ]] && cmp -s -- "$tmp" "$dest"; then
  log "config unchanged, skipping reload"
else
  log "config changed, reloading $service"
fi

“Config unchanged, skipping reload” is the kind of line that saves time later: it records a branch the script took, which is exactly what you cannot reconstruct from the outside.

For anything destructive, a dry-run mode is cheap to add once all side effects go through one function:

bash
run() {
  if [[ $dry_run == 1 ]]; then
    log "would run: $(printf '%q ' "$@")"
  else
    "$@"
  fi
}

run rm -rf -- "$old_release"

printf '%q' quotes each argument the way the shell would need it, so the logged command can be copied and run as-is.

Let a linter read it first

ShellCheck catches most of what this post describes: unquoted expansions, local masking exit statuses, cd without a failure check, and dozens more. Run it in your editor and in CI. Its warning codes, such as SC2086 for an unquoted variable, each have a page explaining the problem, which makes it an unusually good teacher.

Fix warnings rather than disabling them. When a warning really is a false positive, disable that one line with a # shellcheck disable=SC… comment and a reason, so the next reader knows it was deliberate.

Know when to stop

Bash is the right tool for gluing commands together. It is the wrong tool once the script needs data structures, parses anything more structured than lines of text, or has more error states than you can hold in your head. If you find yourself writing a JSON parser in sed, nesting associative arrays, or passing a few hundred lines, that is the point to move to Python or Go. Not because Bash cannot do it, but because the next person to read the script would rather it didn’t.

A template

Put together, the boring defaults fit on one screen:

template.shbash
#!/usr/bin/env bash
set -Eeuo pipefail
trap 'echo "error: line $LINENO: \"$BASH_COMMAND\" exited $?" >&2' ERR

log() { printf '%s %s\n' "$(date -Is)" "$*" >&2; }
usage() { echo "usage: ${0##*/} [-n] <target>" >&2; exit 2; }

dry_run=0
while getopts n opt; do
  case $opt in
    n) dry_run=1 ;;
    *) usage ;;
  esac
done
shift $(( OPTIND - 1 ))
[[ $# -eq 1 ]] || usage
target=$1

run() {
  if [[ $dry_run == 1 ]]; then log "would run: $(printf '%q ' "$@")"; else "$@"; fi
}

workdir=$(mktemp -d)
trap 'rm -rf -- "$workdir"' EXIT

log "starting: target=$target dry_run=$dry_run"
# ...

None of it is interesting, and six months from now, that is what you will want.