Retry a command with exponential backoff
Bash
#!/usr/bin/env bash
# Retry a command with exponential backoff until it succeeds.
set -euo pipefail
retry() {
local max_attempts=$1
local delay=$2
shift 2
local attempt=1
until "$@"; do
if ((attempt >= max_attempts)); then
printf 'giving up after %d attempts: %s\n' "$attempt" "$*" >&2
return 1
fi
printf 'attempt %d failed, retrying in %ss\n' "$attempt" "$delay" >&2
sleep "$delay"
# Double the delay, capped at 30 seconds.
delay=$((delay * 2 > 30 ? 30 : delay * 2))
attempt=$((attempt + 1))
done
}
retry 5 1 curl --fail --silent --show-error -o /dev/null https://example.com/health