Chapter 5: Bash Scripting for Automation
5.10 Debugging scripts without guessing
When a script fails, slow down.
Steps — debug a failing script
- Run with Bash tracing:
bash -x ./health_restart.sh --dry-run— each command prints before it runs. - Check the exit code:
echo $?right after a failure. - Run the failing command alone in the shell (the exact
curlline). - Confirm files and dirs exist:
lsonLOG_DIR,command -v curl. - If cron-only failure: compare
envin SSH vs a cron line that logsenvto a file once.
What you see with bash -x: lines prefixed with + showing expansions. That reveals empty variables and wrong paths faster than staring at the file.
| Failure mode | First fix to try |
|---|---|
| Works in SSH, fails in cron | Absolute paths + log redirect |
unbound variable with set -u |
Export or default the variable (${VAR:-default}) |
permission denied |
Execute bit / correct user for systemctl |
| curl TLS/URL errors | Print "$APP_URL" before curl; fix scheme and port |
Ravindra Bagale's Tip
Script fail zala ki thodach set -e kadhun taku naka. Aadhi -x ne line shodha. Silence = harder bugs. Dhyan rakho!