Systems study
Offline — showing the cached copy.
Home / Linux / 10. Scripts that survive production

10. Scripts that survive production

One-liner. set -euo pipefail, quote everything, clean up with a trap, and be idempotent.

Memorize

  • set -euo pipefail: exit on error, error on unset variables, propagate pipe failures.
  • Quote expansions: "$var", "$@"; IFS=$'\n\t' when splitting matters.
  • trap 'cleanup' EXIT INT TERM for temporary files and partial state.
  • mktemp -d for scratch space; never write predictable names in /tmp.
  • Handle filenames with find … -print0 | xargs -0.
  • Idempotent operations: mkdir -p, rm -f, check-then-act with a lock (flock).
  • shellcheck catches most quoting and portability bugs before production.
SAFE SCRIPT parse args lock trap cleanup do work verify unlock exit code
Safe script

Trap. for f in $(ls) — breaks on spaces, globs, and newlines. Do this. for f in ./*; do or find -print0 | while IFS= read -r -d '' f.

Check

What does set -o pipefail change?