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).
- Shebang +
set -euo pipefail. - Default
APP_URLto your health endpoint (environment can override). curl -fsSthe URL; on success print OK and exit 0.- On failure: if
--dry-runwas passed, print what you would restart and exit 1; else restart the service you actually use in the lab, wait two seconds, curl again. - Log a one-line timestamp result under
~/badge-api-logs/(mkdir -pfirst). - Run once healthy, once with the app stopped (dry-run), once with a real restart if safe.
- 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.