Write a health-check loop that polls a URL until it returns 200, with a timeout.
IntermediateHands-onBash scripting tasks
Answer
#!/usr/bin/env bash
set -euo pipefail
URL="${1:?usage: $0 <url> [timeout]}"
TIMEOUT="${2:-120}"
end=$((SECONDS + TIMEOUT))
until [ "$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$URL")" = "200" ]; do
if (( SECONDS >= end )); then
echo "Timed out after ${TIMEOUT}s waiting for $URL" >&2
exit 1
fi
echo "Waiting for $URL ..."
sleep 5
done
echo "$URL is healthy"
Key trick → $SECONDS is a built-in counter of seconds since the shell started, so no date arithmetic is needed; --max-time stops one hung request from blowing the timeout.
More on Bash scripting tasks
Write the safe header you start every Bash script with, and explain each part.BeginnerWrite a script that alerts when any filesystem is above 80% usage.BeginnerParse an Nginx access log and print the top 10 client IPs by request count.BeginnerWrite a backup script that tars a directory with a timestamp and keeps only the last 7 backups.IntermediateParse command-line flags `-e <env>`, `-v` (verbose) and `-h` in a Bash script.IntermediateUse `trap` to clean up a temp directory on exit, even on Ctrl+C or error.Intermediate