Ravindra BagaleCourses & study guides

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

  1. Add a variable DRY_RUN=0.
  2. If the script receives --dry-run, set DRY_RUN=1.
  3. When health fails, if DRY_RUN=1 print would restart service and exit; else run the real restart command you use in labs (sudo systemctl restart … or your process manager).
  4. 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!