ch09/l03

Script guardrails

Make small scripts fail loudly and leave useful evidence.

set -euo pipefail 25 min read, 35 min lab operator

Scripts should make failure visible. `set -euo pipefail` is not magic, but it catches many common mistakes. Good scripts print what they are about to do, check inputs, and avoid production paths by default.

In the field

You need a repeatable lab cleanup script that refuses to run outside `/tmp/td-*`.

Worked command

$ cat cleanup.sh#!/usr/bin/env bashset -euo pipefailcase "${1:-}" in  /tmp/td-*) rm -ri -- "$1" ;;  *) echo "refusing non-lab path" >&2; exit 2 ;;esac
Anti-pattern

Do not put broad `rm -rf "$1"` in scripts without path checks.

Safer pattern

Validate inputs, print intent, and fail closed.

Knowledge check

Your cleanup script is invoked with no argument. With set -euo pipefail and a case that matches /tmp/td-*, what is the safe behavior?

  • A Default to the current directory and clean it, since no path was given
  • B Match the catch-all branch, print to stderr, and exit nonzero
  • C Silently do nothing and exit 0 so cron does not flag an error
  • D Expand "$1" to an empty string and pass it straight to rm
Show the answer

Correct: B. Match the catch-all branch, print to stderr, and exit nonzero

Why

Fail closed: an unrecognized or missing path hits the *) branch, reports on stderr, and exits nonzero so the failure is visible. Exiting 0 silently hides the problem — automation that swallows failure is the trap these guardrails exist to prevent.

Practice checklist

  1. Write a cleanup script for a disposable directory.
  2. Test it against a safe path and an unsafe path.
  3. Record both outcomes.

Deliverable evidence

  • Script text and two test transcripts.
Teaching diagramch09 · mental model
three layers of safe automation data "$var" quote to keep intact iteration find -print0 | xargs -0 null-delimited names action set -euo pipefail check, print, fail closed leak: word splitting + glob expansion silently corrupt arguments before the action runs exit nonzero, leave evidence

shows: The three safety layers of small shell automation — quoting data, null-safe iteration, and guarded action — and how unquoted or unsplit input leaks corruption into the action stage.

does not prove: It is a model, not a guarantee: set -euo pipefail and quoting reduce common failure classes but do not prove a given script is correct or safe on every input.

Memorize this

Commit these to memory, then drill them until recall is automatic.

set -euo pipefailcaseexit codefail closed
Recall practice · Meaning -> command

cue First line of a small bash script that should abort on errors, unset variables, and broken pipes

show recall target

set -euo pipefail