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




