Failing Well

Failing Well: Errors a User Can Act On, Strict Mode: set -euo pipefail, Cleaning Up: trap and mktemp.

Updated

  1. Errors a User Can Act On (Journeyman): A script people depend on says what went wrong and what to do about it: it prints problems on standard error with >&2, stops with an exit code that means something (0 it worked, 1 it failed, 2 it was run wrong), and keeps those habits in a die function and a usage message.
  2. Strict Mode: set -euo pipefail (Freelancer): set -euo pipefail makes a script stop at the first sign of trouble: -e stops at a command that fails, -u at a variable that was never set, and -o pipefail at a pipeline with a failing part, with a few surprises to know about: a grep that finds nothing, ((count++)) and a missing $1.
  3. Cleaning Up: trap and mktemp (Freelancer): mktemp makes a temporary file or folder with a name no other file has, and trap '...' EXIT runs cleanup however a script ends, Ctrl+C included, so a script that works in a scratch file never leaves half-finished work behind.