Ravindra BagaleCourses & study guides

Chapter 5: Bash Scripting for Automation

5.10 Debugging scripts without guessing

When a script fails, slow down.

Steps — debug a failing script

  1. Run with Bash tracing: bash -x ./health_restart.sh --dry-run — each command prints before it runs.
  2. Check the exit code: echo $? right after a failure.
  3. Run the failing command alone in the shell (the exact curl line).
  4. Confirm files and dirs exist: ls on LOG_DIR, command -v curl.
  5. If cron-only failure: compare env in SSH vs a cron line that logs env to 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!