Chapter 5: Bash Scripting for Automation
5.4 if and loops for health checks
Why. Restart only when health fails — not on every run.
#!/usr/bin/env bash
set -euo pipefail
APP_URL="${APP_URL:-http://localhost:8080/health}"
MAX_TRIES=3
if curl -fsS "$APP_URL" >/dev/null; then
echo "OK: health passed"
exit 0
else
echo "WARN: health failed"
fi
Simple retry loop:
#!/usr/bin/env bash
set -euo pipefail
APP_URL="${APP_URL:-http://localhost:8080/health}"
for i in 1 2 3; do
if curl -fsS "$APP_URL" >/dev/null; then
echo "OK on try $i"
exit 0
fi
echo "Try $i failed — waiting"
sleep 2
done
echo "ERROR: health still failing"
exit 1
What you see: either OK on try N or a final error with exit code 1 — perfect for cron and CI.
Steps — dry-run flag pattern
- Add a variable
DRY_RUN=0. - If the script receives
--dry-run, setDRY_RUN=1. - When health fails, if
DRY_RUN=1printwould restart serviceand exit; else run the real restart command you use in labs (sudo systemctl restart …or your process manager). - Test both modes.
Ravindra Bagale's Tip
Khup students restart nehmi chalavtat — healthy asel tari. Health OK asel tar exit 0; fail zala tarach restart. Unnecessary bounce lunch traffic madhe risk. Dhyan rakho!