Write a function that retries a command up to N times with exponential backoff.
IntermediateHands-onBash scripting tasks
Answer
retry() {
local max="$1"; shift
local n=1 delay=2
until "$@"; do
if (( n >= max )); then
echo "Command failed after $n attempts: $*" >&2
return 1
fi
echo "Attempt $n failed, retrying in ${delay}s..." >&2
sleep "$delay"
n=$((n + 1)); delay=$((delay * 2))
done
}
retry 5 curl -sf https://api.example.com/health
Key trick → "$@" passes the command and its arguments through intact, quoting included, so it works for any command.
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.IntermediateWrite a health-check loop that polls a URL until it returns 200, with a timeout.IntermediateParse command-line flags `-e <env>`, `-v` (verbose) and `-h` in a Bash script.Intermediate