Skip to content

Bash scripting best practices that survive past Tuesday

Write Bash scripts that fail predictably, handle errors, and remain readable — strict mode, traps, quoting discipline, and the patterns that prevent footguns.

You’re inheriting a directory of Bash scripts that nobody trusts. Half of them silently swallow errors with command || true left over from a 2 a.m. patch; the other half delete files with rm -rf "$DIR/" where $DIR was empty once and root was the unintended target. Bash is fine for orchestrating commands — it is bad as a language and worse without discipline. This article is the checklist that turns a *.sh file into something safe to ship.

How to verify

For any existing script, four checks tell you most of what you need:

shellcheck path/to/script.sh
head -5 path/to/script.sh
grep -n 'rm -rf\|eval\|`' path/to/script.sh
bash -n path/to/script.sh

shellcheck is the linter — every warning is a real bug. The head check looks for the strict-mode line. The grep flags the three most common footguns (recursive delete, eval, backtick command substitution). bash -n parses without executing.

What’s happening

Bash has no exceptions and no compile-time type checking. A typo in a variable name resolves to the empty string by default; an exit code from a command in the middle of a pipeline is lost; a glob that matches nothing expands to the literal *. None of this is “safe by default” the way Python’s NameError is safe by default. The fix is to opt in to safer behavior with set flags, quote everything that touches a variable, and treat the script as adversarial input.

The minimum baseline: set -euo pipefail at the top, IFS set explicitly, every variable expansion quoted, every command-substitution that might fail handled with ||, a trap for cleanup, and shellcheck as a pre-commit gate. Anything beyond a one-page script is probably a candidate for a Python rewrite, but for the page-or-less orchestrator role Bash is fine.

The procedure

  1. Open with strict mode and a header. Every script in the repo starts the same way — readers do not have to wonder which mode it’s in.

    #!/usr/bin/env bash
    #
    # rotate-tls-certs.sh — rotate certbot certs, reload Nginx, alert on failure
    # Usage: ./rotate-tls-certs.sh [--dry-run]
    #
    set -Eeuo pipefail
    IFS=$'\n\t'

    -E propagates ERR traps into functions and subshells; -e exits on any non-zero return; -u errors on unset variables; -o pipefail makes a pipeline fail if any stage failed (not just the last).

  2. Quote everything that touches a variable. "$var", not $var. "${array[@]}", not ${array[@]}. "$(command)", not $(command). The single rule covers 90% of the bugs.

  3. Use [[ ... ]] not [ ... ] for tests. The double-bracket is a Bash builtin with pattern-matching, regex, and no word-splitting surprises.

    if [[ -n "${TOKEN:-}" && "${ENV}" == "production" ]]; then
      # ...
    fi
  4. Set a trap for cleanup. Mktemp + trap is the cleanup pattern. The trap also catches ERR and prints a useful error.

    tmpdir="$(mktemp -d)"
    trap 'rc=$?; rm -rf "$tmpdir"; if (( rc != 0 )); then echo "FAIL: line $LINENO rc=$rc" >&2; fi; exit $rc' EXIT
  5. Validate input early. A script that consumes args without checking them is a script that will be run by mistake against the wrong target.

    if [[ $# -lt 1 ]]; then
      echo "Usage: $0 <hostname>" >&2
      exit 2
    fi
    host="$1"
    if [[ ! "$host" =~ ^[a-z0-9.-]+$ ]]; then
      echo "Invalid hostname: $host" >&2
      exit 2
    fi
  6. Use mktemp, not predictable temp paths. /tmp/myscript.lock is a TOCTOU race waiting to happen on a shared host.

  7. Capture stderr separately when it matters. A function that returns a value via stdout should not pollute it with status messages.

    log() { printf '[%s] %s\n' "$(date -Iseconds)" "$*" >&2; }
  8. Functions for any block run twice. Local variables with local to avoid polluting the outer scope.

    reload_nginx() {
      local conf="${1:?conf required}"
      nginx -t -c "$conf"
      systemctl reload nginx
    }
  9. Replace backticks with $(...). Backticks do not nest cleanly and are harder to read.

  10. Lint in CI. A pre-commit config running shellcheck --severity=warning catches the majority of regressions before they merge.

Common pitfalls

  • set -e does not stop a script when a function called inside an if condition fails — that is the design, and it is the most common gotcha.
  • cd "$dir" && rm -rf . becomes cd; rm -rf . if $dir is empty and set -u is not on — quote the variable AND check for emptiness.
  • read -r is almost always what you want; the default read strips backslashes.
  • Iterating a string with for f in $files splits on IFS and globs — use find -print0 | xargs -0 or an array.
  • A SIGINT (Ctrl-C) on a long-running script with no trap leaves the temp directory and any background processes behind — trap '...' EXIT covers both clean and dirty exits.

In the engagements we run, every Bash script that touches production goes through shellcheck in CI, ships with strict mode at the top, and has a --dry-run flag for first invocation. For anything beyond orchestration, we reach for Python or Go. See /en/services/managed-operations/.