Ravindra BagaleCourses & study guides

Chapter 5: Bash Scripting for Automation

5.8 Reading arguments and a full sample script

Scripts become useful when they accept flags.

#!/usr/bin/env bash
set -euo pipefail

DRY_RUN=0
APP_URL="${APP_URL:-http://localhost:8080/health}"
SERVICE_NAME="${SERVICE_NAME:-badge-api}"
LOG_DIR="${HOME}/badge-api-logs"

for arg in "$@"; do
  case "$arg" in
    --dry-run) DRY_RUN=1 ;;
    --url=*) APP_URL="${arg#*=}" ;;
    *) echo "Unknown arg: $arg" >&2; exit 2 ;;
  esac
done

mkdir -p "$LOG_DIR"
ts="$(date -Iseconds)"

if curl -fsS "$APP_URL" >/dev/null; then
  echo "$ts OK $APP_URL" | tee -a "$LOG_DIR/health.log"
  exit 0
fi

echo "$ts FAIL $APP_URL" | tee -a "$LOG_DIR/health.log"

if [[ "$DRY_RUN" -eq 1 ]]; then
  echo "DRY-RUN: would restart $SERVICE_NAME"
  exit 1
fi

sudo systemctl restart "$SERVICE_NAME"
sleep 2
curl -fsS "$APP_URL" >/dev/null
echo "$ts RESTARTED_OK $SERVICE_NAME" | tee -a "$LOG_DIR/health.log"

Why this shape. Defaults in the environment, explicit --dry-run, logs with timestamps, restart only after failure, second curl to verify. Swap systemctl for your real lab process if you are not using systemd yet.

Steps — test the sample safely

  1. Save as ~/bin/health_restart.sh and chmod u+x it.
  2. Export APP_URL to a URL that works on your machine.
  3. Run ./health_restart.sh --dry-run while the app is stopped — you should see DRY-RUN, not a restart.
  4. Start the app; run without --dry-run — expect OK.
  5. Read ~/badge-api-logs/health.log.

Ravindra Bagale's Tip

tee -a screen aani file donhi update karte — cron debug sathi useful. Fakt >> asel tar live output dista nahi. Lakshat theva!