Retry With Exponential Backoff
Retry a shell command with exponential backoff and a bounded attempt count, failing loudly when exhausted.
Code
#!/usr/bin/env bash
set -euo pipefail
retry() {
local max_attempts="$1"; shift
local delay=1
local attempt=0
until "$@"; do
attempt=$((attempt + 1))
if (( attempt >= max_attempts )); then
echo "retry: giving up after ${attempt} attempts" >&2
return 1
fi
echo "retry: attempt ${attempt} failed, sleeping ${delay}s" >&2
sleep "$delay"
delay=$((delay * 2))
done
}
# 用法示例:最多 5 次,命令失败时按 1s、2s、4s、8s 退避
retry 5 curl -fsS --max-time 10 https://api.example.com/healthReport a problem with this exampleOpens a pre-filled issue on GitHub.