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 TERMfor temporary files and partial state.mktemp -dfor 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). shellcheckcatches most quoting and portability bugs before production.
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?
Why
Without it, false | true succeeds; pipefail propagates the first non-zero status.