The Bash Scripting Playbook
The Anatomy of a Production Script
Every production bash script follows the same skeleton. Here's the template that senior engineers use as a starting point:
#!/bin/bashset -euo pipefail# Exit on error, undefined vars, pipe failsTARGET_DIR="/var/backups"# Variables at the topLOG_FILE="/var/log/backup.log"mkdir -p "$TARGET_DIR"# Idempotent setupfor f in *.log; do# Process filesΒ Β cp "$f" "$TARGET_DIR/"doneecho "Done at $(date)"# Always log completion
π‘οΈ Best Practices
set -eβ Exit on any errorset -uβ Error on undefined variables- Always quote
"$variables" - Use
UPPER_CASEfor constants - Add echo statements for logging
β° Cron Cheat Sheet
* * * * *β Every minute*/5 * * * *β Every 5 minutes0 2 * * *β Daily at 2:00 AM0 0 * * 0β Weekly (Sunday midnight)0 0 1 * *β Monthly (1st at midnight)
β οΈ Common Bash Gotchas
- β
VAR = valueβ spaces cause "command not found". UseVAR=value - β
if[$x == $y]β missing spaces. Useif [ "$x" == "$y" ] - β Unquoted
$varwith spaces β word splitting breaks paths - β Missing shebang β script runs in wrong shell with wrong syntax
- β Relative paths in cron β cron runs in minimal environment without $PATH




