Shell Scripting Patterns for Reliable Scripts
A few defensive patterns make the difference between fragile scripts and ones you can trust in production.
Key Insights
- Always start with set -euo pipefail for fail-fast behavior
- Use trap for cleanup to avoid leaving temporary files or zombie processes
- Quote all variable expansions to prevent word splitting bugs
The Defensive Header
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
Cleanup with Trap
tmpfile=$(mktemp)
trap 'rm -f "$tmpfile"' EXIT
curl -s "$url" > "$tmpfile"
process "$tmpfile"
# tmpfile is cleaned up automatically
Safe Variable Usage
# Always quote
cp "$source" "$destination"
# Default values
name="${1:-default}"
# Required variables
: "${API_KEY:?API_KEY must be set}"