Overview
Start with the conclusion: an exit code of 0 does not mean the script behaved. That sounds obvious, yet every year it burns someone in a production environment in a slightly different way.
Last year, on an e-commerce order fulfillment system, I hit this: a cleanup script that ran every night at 1 a.m. and pruned old release directories under /data/apps/order-api/releases/. It had run for two years with nothing but a clean clean done in the log. Then, during a pre-sale scale-out, six new Pods all landed in CrashLoopBackOff with a single error line: exec: /data/apps/order-api/releases/20261127-1/bin/order-api: no such file or directory.
The directory was gone. It had been gone for three days. Production had been perfectly healthy in those three days — because the running process had already loaded the executable into memory. Linux lets you delete a file that is still open; the process keeps running, it just cannot start a second copy.
That is what makes delayed failures so nasty: the moment the script exits successfully, the fuse is already lit, but you only hear the bang at the next restart, scale-out, or deploy. Three days of separation, a very long causal chain, and almost nobody thinks to scroll back through three days of cron logs.
This post covers two things:
- What actually happened that night, and why a script that clearly had quotes in it deleted something it should not have.
- The seven-item pre-production audit I now enforce across teams, each item tied to a concrete way scripts destroy things rather than to an abstract “best practice”.
Every item comes with the matching ShellCheck rule number, because human review does not scale — people get tired, get distracted, and tell themselves “it’ll be fine this time.” Tools don’t.
The incident: a deletion with exit code 0
The log at 01:12
The script looked roughly like this, and looked fine:
#!/bin/bash
# Runs from crontab at 01:00 daily: prune old releases, keep only what current points to
APP_ROOT=/data/apps/order-api
CURRENT=$(readlink "$APP_ROOT/current")
for dir in "$APP_ROOT"/releases/*; do
if [ "$dir" != "$CURRENT" ]; then
rm -rf "$dir"
fi
done
echo "clean done"
Variables quoted, an if present, and clean done printed at the end. Everything signals “this script is solid”.
The problem sits on line two. Normally readlink returns /data/apps/order-api/releases/20261127-1, matching $dir on the current release, so it is skipped and the older ones get removed — exactly as designed.
That night, however, current was broken. A failed deploy the previous afternoon had pointed current at releases/20261128-1 before that directory was fully published. The rollback restored the process but not the symlink, leaving a dangling symlink.
So readlink happily returned that non-existent path. Note the exit code — it is 0:
| Step | Actual value | Consequence |
|---|---|---|
readlink current | /data/apps/order-api/releases/20261128-1, exit 0 | CURRENT holds a path that does not exist |
[ "$dir" != "$CURRENT" ] | Neither existing release equals it | Every release takes the delete branch |
rm -rf "$dir" | Runs per release, all succeed | Including the live 20261127-1 |
| Script exit code | 0 (last command is echo) | Health checks and alerts stay green |
No step failed. This is not “a command failed and we ignored it” — every step genuinely succeeded, and adding set -e on line one would not have stopped a single one of them. That is the part that trips people up.
I reproduced it on a test box in a dozen lines of shell. Real output:
$ readlink "$W/current"
/tmp/tmp.27OAFm8DL2/releases/20261128-1
readlink exit code=0
$ bash clean.sh "$W"
clean done
cleanup script exit code=0
$ ls -1 "$W/releases"
(empty)
The release production was using is gone, and the exit code is still 0.
There is a second, equally common variant: if current does not exist at all (deleted, or never created on a new cluster), readlink returns 1 with empty output, CURRENT="", and [ "$dir" != "" ] is always true — same total deletion. The damage is identical; only the failure point differs. Which means “did any command report an error?” is the wrong question to build defenses around.
Why the bang came three days later
Here is the blind spot I keep running into: a process and its file are two different things.
At startup, the kernel maps the ELF header and code segments into memory. The executable on disk is just an inode that has been opened. rm removes the directory entry; the inode survives because the process holds a file descriptor. lsof shows it clearly:
order-api 23177 root txt REG 253,1 48234496 1234567 /data/apps/order-api/releases/20261127-1/bin/order-api (deleted)
The full signal chain looked like this:
| Time | Event | What the system showed |
|---|---|---|
| D 15:40 | Deploy fails; rollback restores the process, symlink left at 20261128-1 | Pipeline final status: success |
| D 01:12 | Cleanup script deletes every release directory, including 20261127-1 | One log line clean done, exit 0 |
| D+1, all day | Traffic normal, process holds fd of deleted file | All SLIs normal, zero alerts |
| D+2, all day | Same | Same |
| D+3 10:05 | Scale out six replicas before the sale | Four Pods CrashLoopBackOff |
CPU normal, QPS normal, no alerts. The failure was deferred to the next moment something needed that file — a container restart, a node scale-out, a deploy, even a restart after an OOM kill.
For three days everyone believed the system was fine. The risk was real, and no metric expressed it. That is exactly why audit item five insists cleanup scripts default to dry-run: the operation is irreversible and its failure may stay invisible for days. You cannot count on discovering it afterwards.
Why “I quoted the variable” is not safety
Most people’s safety instinct stops at “quote your variables”. True, but that only fixes my file.txt being split into two arguments.
Quotes stop word splitting, not emptiness
F="my file.txt"
rm $F # expands to rm my file.txt → deletes two files
rm "$F" # correct, deletes one
That is the case quotes rescue. The incident script was already quoted and still failed:
EMPTY=""
rm -rf "$EMPTY"/* # expands to rm -rf /* ← quotes cannot help
Not a thought experiment. In 2015, Steam for Linux wiped users’ home directories with rm -rf "$STEAMROOT/"* — perfectly quoted, with STEAMROOT empty.
Quotes are a label on a parcel saying “this is one item”, preventing it from being split. But if the parcel is empty, a correctly applied label still ships nothing. What a destructive command needs against empty values is not a label but address validation: confirm the target is legitimate and inside a whitelisted directory before touching it.
One principle instead of endless quoting arguments
The target path of a destructive command must be computed and validated by the script itself — never taken directly from external input or from a command substitution that can fail.
In practice: resolve the target, validate the boundary, print the target, then act. That is audit item five.
Audit 1: variable existence and validity (SC2154 / SC2086)
set -u turns references to undefined variables into failures — the cheapest layer available:
#!/usr/bin/env bash
set -u
TARGET_DIR="" # explicitly assigned empty: set -u cannot see this
rm -rf "$TARGET_DIR"/* # still deletes root
Note the trap: set -u only catches “never defined”, not “defined but empty”. What actually guards emptiness is parameter expansion with an assertion:
# ${VAR:?msg} exits immediately if the variable is unset or empty, printing msg to stderr
APP_ROOT="${APP_ROOT:?APP_ROOT must be set, refuse to continue}"
BASE="${BASE:-/data/apps}" # use :- only where a sane default exists; never for destructive paths
Pair it with semantic validation — emptiness is just one kind of invalid value:
# Only allow release ids like 20261127-1; never let path concatenation produce surprises
if [[ ! $RELEASE_ID =~ ^[0-9]{8}-[0-9]+$ ]]; then
echo "invalid RELEASE_ID: $RELEASE_ID" >&2
exit 2
fi
target="$BASE/releases/$RELEASE_ID"
A word on cron. APP_ROOT was hardcoded in the incident script, which saved it; a sibling script in the same batch read its path from an environment variable and got an empty value under cron — because cron does not inherit your login shell environment. It only sees /etc/environment, /etc/cron.d file headers, and explicit VAR=value lines in the crontab. A script that works perfectly in your terminal becomes a different program under cron. That is the classic source of “passes locally, fails silently in production”.
My rule: ops scripts get no implicit environment dependencies. Either export explicitly inside the script, or run under a systemd timer (Environment= / EnvironmentFile= make it explicit, and you also get timeouts, journal logging, and restart policy). Across the projects I have taken over, I have moved critical scheduled ops tasks from cron to systemd timers — not for novelty, but because during an incident, “what exactly was the environment?” must be answerable. I covered the comparison in Related: Scheduled Task Management: cron vs systemd timer.
Audit 2: three blind spots of set -e (SC2155 / SC2181)
Treating set -e as a safety switch is the single most common misconception. It has three reliable blind spots.
set -e
# Blind spot 1: commands in conditional context never trigger the exit
if grep -q ERROR app.log; then # grep returning 1 is normal; set -e does not apply
echo "there were errors"
fi
# Blind spot 2: local/declare with command substitution masks the command's exit code (SC2155)
local ts=$(date +%s) # if date failed, you will never know
# Blind spot 3: a function's failure is swallowed by the caller's condition
check_env && deploy # if the first command inside deploy fails, the function
# returns non-zero, but the whole line sits in && context
Plus the fourth lesson from the incident: when every step succeeds, set -e has no failure to catch. It guards against “a command failed but execution continued”, not against “all commands succeeded and produced the wrong outcome”.
So for destructive scripts my position is explicit: do not rely on set -e as the only line of defense. Keep it, but write every critical step as an explicit if ! cmd; then exit N; fi, so failure paths are readable, distinguishable, and carry their own exit codes:
# Failures inside a command substitution must be checked manually; otherwise they vanish
if ! CURRENT="$(readlink -f -- "$APP_ROOT/current")"; then
echo "cannot resolve current symlink, abort" >&2
exit 3
fi
set -e’s “sometimes it catches it, sometimes it doesn’t” semantics cannot be inferred by someone reading the code, which leaves only guessing during an incident. Error handling a human can read beats clever error handling.
Audit 3: swallowed pipeline errors (SC2312)
In a | b | c, the exit code equals c’s. If everything upstream dies and the last stage succeeds, the pipeline reports success.
This is exactly what caused Cloudflare’s well-known slowdown in 2020: a Bash script in a Kubernetes CronJob generated configuration via dos-make-addr-conf | dosctl. When the upstream API call failed, its output was empty, and the second stage dutifully wrote an empty string into a config key. An empty string is a valid TOML document, so downstream loaded it as real configuration and front-line routing decisions went sideways.
The fix is one line:
set -o pipefail # any failing stage fails the whole pipeline
But pipefail has a counterintuitive side effect that shows up constantly in ops scripts:
set -euo pipefail
count=$(grep -c "OOM" app.log) # no match makes grep return 1 → the script exits
grep returning 1 means “nothing matched”, not “something broke”. Under pipefail plus set -e that gets treated as fatal. So every query where zero matches is legitimate needs explicit tolerance:
count=$(grep -c "OOM" app.log || true)
# or tolerate exactly 1, and let every other error propagate
count=$(grep -c "OOM" app.log) || [[ $? -eq 1 ]]
The second form is noisier but more precise: if app.log does not exist (grep returns 2), the script still stops.
One debugging trick worth memorizing: PIPESTATUS exposes every stage’s exit code.
tar cf - /data/app | ssh backup01 'cat > /backup/app.tar'
echo "${PIPESTATUS[@]}" # e.g. "2 0": tar failed, ssh succeeded
That one line saves the half hour you would otherwise spend asking “why is this backup empty?”
Audit 4: expansion and globbing (SC2086 / SC2046 / SC2012)
Shell expands first, then runs the command. Quotes block word splitting and globbing, but they cannot stop “expansion produces an empty argument” or “expansion produces something starting with - that gets parsed as a flag”.
Three recurring shapes:
# Shape 1: unquoted variable (SC2086)
cp $SRC $DST # SRC="/a b/c" splits immediately
# Shape 2: unquoted command substitution (SC2046)
rm -rf $(ls /tmp/*.log) # a filename with a space turns this into a disaster
# Shape 3: looping over ls output (SC2012)
for f in $(ls *.log); do # spaces, newlines, leading dashes all break it
gzip "$f"
done
The correct fix for shape 3 is not “add quotes” but change the data source:
# Globs plus quotes: spaces in filenames are safe by construction
for f in /var/log/app/*.log; do
[[ -e $f ]] || continue # with no match the glob is returned literally; guard it
gzip -- "$f"
done
# Filenames containing newlines: find -print0 with read -d ''
while IFS= read -r -d '' f; do
gzip -- "$f"
done < <(find /var/log/app -maxdepth 1 -name '*.log' -print0)
The -- marker deserves its own note. It tells the command “stop parsing options here”, which is the last gate before path safety:
rm -rf -- "$target" # even if target is "-rf" or "-x", it is not parsed as a flag
Do not skip [[ -e $f ]] || continue either. With no matches, Bash hands the literal *.log to the loop body, and you end up gzipping a file named *.log — with an error message that makes no sense.
Audit 5: target validation for destructive commands
The first four items surface errors. This one limits damage even when errors do not surface. For rm -rf, find -delete, truncate, and > existingfile, I require three things of a script: compute the target itself, validate the target is in scope, print the target before acting.
The rebuilt incident script:
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
APP_ROOT="${APP_ROOT:?APP_ROOT required}"
BASE="$APP_ROOT/releases"
KEEP=3 # keep the newest 3 releases, not just current
DRY_RUN="${DRY_RUN:-1}" # default is print-only, never delete by default
[[ -d $BASE ]] || { echo "base dir missing: $BASE" >&2; exit 2; }
BASE="$(cd -- "$BASE" && pwd -P)" # canonical absolute path, removing symlink ambiguity
# Resolve current. Note readlink -f still exits 0 on a dangling symlink,
# so what actually catches "points at a missing directory" is the -d check below,
# not readlink's exit code.
CURRENT="$(readlink -f -- "$APP_ROOT/current" 2>/dev/null || true)"
[[ -n $CURRENT && -d $CURRENT && $CURRENT == "$BASE"/* ]] || {
echo "resolved current '$CURRENT' invalid or missing, refuse to clean" >&2
exit 3
}
# Sort releases by name, newest first, then force current into the keep list
mapfile -t all < <(find -- "$BASE" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort -r)
keep_list=("$CURRENT")
for d in "${all[@]}"; do
[[ ${#keep_list[@]} -ge $KEEP ]] && break
keep_list+=("$BASE/$d")
done
for d in "${all[@]}"; do
target="$BASE/$d"
skip=0
for k in "${keep_list[@]}"; do [[ $target == "$k" ]] && skip=1 && break; done
(( skip )) && continue
# Final check: target must be strictly one level under BASE and must not equal BASE
[[ $target == "$BASE"/* && $target != "$BASE" ]] || {
echo "refuse: suspicious target '$target'" >&2; exit 4
}
if [[ $DRY_RUN == 1 ]]; then
echo "[dry-run] would remove: $target"
else
echo "removing: $target"
rm -rf -- "$target"
fi
done
The script is ten times longer than the original. Worth it? Yes. It writes my judgment into assertions in the code instead of leaving it in the operator’s attention at 1 a.m. What breaks things is never the obvious case; it is “a previous deploy left a broken symlink” — a state nobody predicted.
Two hard rules:
- Cleanup scripts default to
DRY_RUN=1. Deleting in production requires an explicitDRY_RUN=0. With a default-safe script, an accidental trigger costs you a log line, not a directory. - No
find ... -exec rm {} \;patterns.-execruns in the script’s working directory, and path resolution has a TOCTOU window (what you checked and what you delete may not be the same object). Use-execdirwhen you need per-directory execution, or collect, validate, then delete as above.
One related trap with find -delete: find "$BASE" -mtime +7 -delete without -mindepth 1 will match $BASE itself (its mtime can easily be old), deleting the entire base directory. Whenever a directory is the search root, -mindepth 1 is mandatory.
Audit 6: concurrency and locking
Overlapping scheduled runs are another “fine for years, then a mess” class. The script normally finishes in 40 seconds; one day the source is slow and it takes four minutes while cron fires every two, so three instances run the same cleanup logic — one deleting, one traversing, find losing targets mid-walk, exit codes scrambled, logs overwriting each other.
PID files are unreliable (the process dies and the file remains; PID values get reused). Use flock:
LOCK=/var/lock/clean-releases.lock
exec 9>"$LOCK"
if ! flock -n 9; then
echo "another run in progress, skip" >&2
exit 0 # skipping is not a failure; keep it out of alerting
fi
exec 9>file attaches the lock file to fd 9, and flock -n returns immediately if the lock is held. When the process exits, fd 9 closes and the lock is released — no cleanup logic, no stale lock files.
The exit 0 detail matters: a concurrent skip is not an incident, and returning 0 keeps it out of alerts. Exit codes in ops scripts should carry meaning: 0 success, 0 skipped, non-zero for distinct failure classes (2 bad arguments, 3 invalid state, 4 suspicious target). Alert rules built on that semantics are far more accurate than rules built on “the script reported an error”.
Audit 7: temp files and signal cleanup
The lightest item, but skipping it leaves garbage on disk — or worse, leaves a half-written file that a downstream consumer reads as complete data.
#!/usr/bin/env bash
set -Eeuo pipefail
TMP="$(mktemp -d "${TMPDIR:-/tmp}/clean.XXXXXX")" || exit 1
# The trap body must use single quotes so the variable expands at exit time (SC2064)
trap 'rm -rf -- "$TMP"' EXIT INT TERM
dump="$TMP/app.tar"
tar cf -- "$dump" /data/app
# Validate, then rename: partial artifacts never appear at the final path
[[ -s $dump ]] || { echo "dump empty, abort" >&2; exit 5; }
mv -- "$dump" /backup/app.tar
Single quotes in trap ... EXIT are the heart of SC2064: with double quotes, $TMP expands at the moment the trap is installed and will not follow later changes. I have seen this written with double quotes at least five times in code review.
Also: mktemp -d creates a directory with mode 700, far safer than mkdir /tmp/xxx. Fixed-name files under /tmp (/tmp/out.log) are a classic collision source in multi-instance deployments and a well-known symlink attack entry. Pre-creating a symlink at a predictable path and waiting for your script to write through it is an old trick.
The seven audits at a glance
I turned this into a checklist for code reviews:
| # | Audit item | One-line check | Rules | If skipped |
|---|---|---|---|---|
| 1 | Variable existence and validity | Destructive paths use ${VAR:?} plus format validation | SC2154, SC2086 | Empty or dirty values delete the wrong thing |
| 2 | set -e blind spots | Critical steps use explicit if ! cmd | SC2155, SC2181 | Failures swallowed by conditions or local |
| 3 | Pipeline error swallowing | set -o pipefail; zero-match queries tolerated explicitly | SC2312 | Upstream failure writes empty data downstream |
| 4 | Expansion and globbing | No unquoted variables or substitutions; no ls-driven loops | SC2086, SC2046, SC2012 | Spaces, newlines, leading dashes break everything |
| 5 | Destructive command guardrails | Dry-run by default; target validated under base dir | — | Irreversible deletion, possibly discovered days later |
| 6 | Concurrency and locking | flock; skip returns 0 | — | Instances trample each other; logs and codes scrambled |
| 7 | Temp files and signals | mktemp; trap uses single quotes | SC2064 | Partial artifacts read as complete data |
ShellCheck rules worth knowing by number
| Rule | Meaning | Typical fix |
|---|---|---|
| SC2086 | Unquoted variable; splitting and globbing | rm "$dir" |
| SC2046 | Unquoted command substitution | "$(cmd)" |
| SC2155 | local/declare with assignment masks exit code | local v then v=$(cmd) |
| SC2181 | Indirect check via [ $? -eq 0 ] | if cmd; then |
| SC2012 | Using ls output for processing | Globs or find -print0 |
| SC2064 | trap with double quotes expands early | trap 'cmd "$var"' EXIT |
| SC2312 | Pipeline exit code ignored | set -o pipefail or inspect PIPESTATUS |
| SC2154 | Referencing an unassigned variable | Assign it or use ${VAR:-default} |
Turning the audits into a gate
A checklist in a document dies within three months. So I put two automated layers in place.
The first is the editor and local commits: ShellCheck installed, editor plugin flagging in real time, a pre-commit hook in the repo.
The second is CI, and it is the layer that actually works:
# .gitlab-ci.yml excerpt
shellcheck:
stage: lint
image: koalaman/shellcheck-alpine:v0.10.0
script:
- find scripts ops -type f -name '*.sh' -print0
| xargs -0 -r shellcheck --severity=warning --format=gcc
allow_failure: false
Three details decide whether the gate survives:
| Decision | My choice | Rationale |
|---|---|---|
| Severity threshold | --severity=warning | error + warning is the “will hurt you” set; blocking on info/style turns all legacy scripts red at once and the team simply disables the gate |
| Version pinning | Pin the ShellCheck version | New rules make “green yesterday” pipelines red overnight; that noise destroys trust |
| Exemptions | Inline # shellcheck disable=SC2086 plus a reason comment | A global disable in .shellcheckrc is a rule turned off with nobody noticing |
On exemptions I am fairly strict: an exemption must carry a reason and an expiry mindset. disable=SC2086 followed by “paths guaranteed space-free by upstream, refactor due 2026-09” gets collected in three months; a bare disable=SC2086 is a hole punched in the gate, and holes are easier to use than gates. Everyone will use the hole.
Do not get the legacy-script order wrong either. Turning on strict mode across the whole repo at once produces hundreds of findings, and the team’s first instinct is to disable the check. My three-phase approach:
- Only scan the delta at first: CI gates the
.shfiles changed in each merge request. - Then sweep directories by existing code, clearing
errorfirst and sortingwarningby execution frequency (daily scheduled jobs first). - Finally pipe ShellCheck results into the existing inspection report so they have an owner, like disk, certificates, and process liveness.
Step three needs something executable behind it, otherwise “pipe into the report” is just a sentence. My script is deliberately boring — one file at a time, sorted output:
#!/usr/bin/env bash
# audit-scripts.sh: scan scripts in bulk and summarize, error → warning → info
set -Eeuo pipefail
ROOT="${1:?usage: audit-scripts.sh <dir>}"
REPORT="${2:-/tmp/shell-audit.txt}"
: > "$REPORT"
find -- "$ROOT" -path '*/.git' -prune -o -type f -name '*.sh' -print0 \
| while IFS= read -r -d '' f; do
out="$(shellcheck --severity=info --format=gcc -- "$f" 2>&1 || true)"
[[ -z $out ]] && continue
printf '%s\n' "$out" >> "$REPORT"
done
# Summary: counts per severity, and the top 10 most-flagged files
grep -oE ': (error|warning|info):' "$REPORT" | sort | uniq -c
grep -oE '^[^:]+' "$REPORT" | sort | uniq -c | sort -rn | head -10
That third step looks unrelated to script safety, but it is the crux. An alert without an owner is not an alert — true in monitoring, equally true in code gates. I wrote about the platform trade-offs in Related: From “@ Ops in Chat” to Self-Service: 6-Layer Architecture for Platformizing 20+ Operations.
Before and after: measured numbers
Same system, 34 ops scripts (11 of them daily scheduled jobs), before and after over comparable windows:
| Metric | Before (6 months) | After (6 months) |
|---|---|---|
| ShellCheck error + warning findings | 148 | 9 (all exemptions with documented reasons) |
| Production incidents caused by scripts | 3 (including one P1 data-directory deletion) | 0 |
| Scheduled-job “silent failures” (exit 0, wrong result) | at least 5 | 1 (now covered by an assertion) |
| Average time to diagnose a single script issue | ~40 minutes | ~12 minutes |
| Script line count | ~2,100 | ~2,900 (the delta is validation and logging) |
That last row deserves a note: the scripts got longer, and that is the correct outcome. Nearly all of the extra 800 lines are parameter validation, boundary assertions, dry-run branches, and structured logging. Ops scripts should not be measured by “does it run” but by “can it prove it did the right thing when something goes wrong”. My line to the team: better an ugly, long script than a clever, silent one.
The final step was more radical: the few dozen high-repetition operations (prune directories, rotate logs, verify certificates, pull config) moved into our own ops platform and now run through a Go scheduler, with the script reduced to a task definition. The platform provides dry-run, approval, execution history, and audit inherently — guardrails that cost a dozen lines in shell are configuration fields there. That is the direction I keep recommending: operations that a platform can carry should not stay in “a script on someone’s laptop” indefinitely.
Three priorities if you are new to ops
If you can only change three things, this order:
- Add
${VAR:?}and boundary validation to every destructive path; make cleanup scripts dry-run by default. This blocks irreversible loss — the highest return. set -Eeuo pipefailplus explicitif ! cmd; then exit N; fion critical steps. This blocks silent failure, surfacing problems in the minute they happen rather than three days later.- Gate ShellCheck at
warning, and addflockandtrap. This blocks long-term decay and costs almost nothing — one CI job.
Style concerns — naming, comments, log formats — come after those three. Reverse the order and you end up with beautiful code that once deleted a production directory. For existing Bash conventions see Related: Production-Grade Bash Scripting Guide and Related: Practical Shell Script Automation Tips; both cover “how to write it well”, while this post is about “how to guarantee it cannot wreck things”.
Common objections: “we only have a handful of scripts”
The most frequent pushback I hear in review meetings. Point by point:
“It’s about ten scripts, we can eyeball them.” The incident script was 30 lines, untouched for two years, and everyone had read it. Reading it once and re-reading it on every change are different things — and the danger of destructive scripts is precisely that the environment changes while nobody edits the script.
“Quotes and set -e should be enough.” The reproduction above shows every command succeeded, so set -e had nothing to do. Empty values, dangling symlinks, and bad path concatenation are semantic errors, not syntax errors. Static analysis catches some; assertions catch the rest.
“ShellCheck reports a pile of stuff, fixing it is exhausting.” Which is why I suggest gating only the delta and only warning. Most codebases have surprisingly little legacy debt. What is truly unbounded is usually info/style, and those should not block anyway.
“Just rewrite it in Python or Go.” A language gives you types and exception propagation, but it does not tell you whether this directory should be deleted at all. I have seen os.RemoveAll(base + "/" + releaseID) with a broken path in Go platforms too. A language does not buy judgment; guardrails do.
Summary
Back to that script. Every line was defensible on its own: quotes present, condition written, log printed. What broke it was four locally-correct decisions stacking into a systemic gap: a dangling symlink made readlink successfully return a path that did not exist, an empty-ish value in a comparison marked every directory as deletable, deletion had no boundary check, and the trailing echo washed the exit code to 0.
The danger of shell scripts is not syntax. It is that they fail silently. No type system, no stack traces, no compile-time checks; the default behavior is “a command failed, keep going”. So the bar for an ops script cannot be “it runs” — it has to be one level up: can it prove it did the right thing?
My practice comes down to three sentences:
- Safe by default: cleanup deletes nothing unless explicitly switched on.
- Loud by default: every failing step gets its own exit code and stops immediately; do not expect
set -eto cover everything. - Auditable by default: whatever you cannot gate by convention, gate with ShellCheck and CI; human review handles only what tools cannot.
The real reason nobody noticed for three days was not a lack of monitoring. It was that nothing in the system expressed “this release directory must not be deleted”. Adding that expression is worth more than three extra alerts.
References & Acknowledgments
This article drew on the following sources. Thanks to the original authors:
- ShellCheck - A shell script static analysis tool — Koalaman / the ShellCheck project; referenced rule categories, severity definitions, CI integration, and the official dangerous-pattern examples such as
rm -rf "$VAR/"* - shellcheck(1) — Debian Manpages — Debian project; verified
--severityvalues, exit code semantics (0/1/2/4), andSHELLCHECK_OPTSusage - Integrating with ShellCheck — ShellCheck Wiki; referenced machine-readable output formats (JSON / GCC style) and the integration checklist used to design the CI gate
- PIPEFAIL: How a missing shell option slowed Cloudflare down — Cloudflare Engineering blog; the real incident behind the pipeline section
- Why your bash script breaks on spaces — and deletes the wrong file — KODiQ; the classic empty-variable-plus-quotes analysis, including the Steam for Linux incident
- Google Shell Style Guide — Google; referenced its notes on the limits of
set -eand script readability conventions