Ravindra BagaleCourses & study guides

Chapter 5: Bash Scripting for Automation

5.11 Lab — health check script with dry-run

Lab

Build health_restart.sh for your badge API hello API (local Docker/Node/Python or a small service on your VM).

  1. Shebang + set -euo pipefail.
  2. Default APP_URL to your health endpoint (environment can override).
  3. curl -fsS the URL; on success print OK and exit 0.
  4. On failure: if --dry-run was passed, print what you would restart and exit 1; else restart the service you actually use in the lab, wait two seconds, curl again.
  5. Log a one-line timestamp result under ~/badge-api-logs/ (mkdir -p first).
  6. Run once healthy, once with the app stopped (dry-run), once with a real restart if safe.
  7. Optional: add a cron line that runs every five minutes with log redirect — remove the cron entry when the lab ends.

Practice task

List three reasons a script that works in your SSH session can fail under cron. Fix each with one concrete habit (absolute path, env, logging).

Thodkyaat sangaycha tar

  • Bash scripts turn repeated ops into a file: shebang, set -euo pipefail, clear exit codes.
  • Variables + quotes; if / loops for health; restart only when needed.
  • Aim for twice-safe scripts (mkdir -p, check before install).
  • Cron needs absolute paths and logs; interactive PATH is not guaranteed.
  • Secrets stay in the environment / secret stores — never in committed scripts.

Samajla ka? Nasel tar health script lab (5.11) dry-run mode sodun puurn kara – curl fail zala tarach restart. Aata pudhe jaauya Docker images aani containers kade.