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/healthHow the snippet works
The shebang line is backed by set -euo pipefail: first failure stops the run, unset variables are errors, and a pipeline fails if any stage fails.
The work is delegated to sleep and retry, chained so each stage’s output feeds the next.
A helper function (retry) keeps the repeated logic out of the main flow.
Key statements worth quoting
attempt=$((attempt + 1))
if (( attempt >= max_attempts )); then
echo "retry: giving up after ${attempt} attempts" >&2
delay=$((delay * 2))
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `sleep`, `retry` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.