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
-
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'-EpropagatesERRtraps into functions and subshells;-eexits on any non-zero return;-uerrors on unset variables;-o pipefailmakes a pipeline fail if any stage failed (not just the last). -
Quote everything that touches a variable.
"$var", not$var."${array[@]}", not${array[@]}."$(command)", not$(command). The single rule covers 90% of the bugs. -
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 -
Set a trap for cleanup. Mktemp + trap is the cleanup pattern. The trap also catches
ERRand 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 -
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 -
Use
mktemp, not predictable temp paths./tmp/myscript.lockis a TOCTOU race waiting to happen on a shared host. -
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; } -
Functions for any block run twice. Local variables with
localto avoid polluting the outer scope.reload_nginx() { local conf="${1:?conf required}" nginx -t -c "$conf" systemctl reload nginx } -
Replace backticks with
$(...). Backticks do not nest cleanly and are harder to read. -
Lint in CI. A
pre-commitconfig runningshellcheck --severity=warningcatches the majority of regressions before they merge.
Common pitfalls
set -edoes not stop a script when a function called inside anifcondition fails — that is the design, and it is the most common gotcha.cd "$dir" && rm -rf .becomescd; rm -rf .if$diris empty andset -uis not on — quote the variable AND check for emptiness.read -ris almost always what you want; the defaultreadstrips backslashes.- Iterating a string with
for f in $filessplits onIFSand globs — usefind -print0 | xargs -0or an array. - A SIGINT (Ctrl-C) on a long-running script with no trap leaves the temp directory and any background processes behind —
trap '...' EXITcovers 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/.