Curl Retry Backoff Transient Errors
Retry curl against flaky endpoints with retry flags, exponential backoff, and server-side Retry-After header respect.
Code
#!/usr/bin/env bash
set -euo pipefail
readonly URL="https://api.example.com/v1/report"
readonly MAX_RETRIES=4
fetch_report() {
local attempt=0
local wait=1
while (( attempt < MAX_RETRIES )); do
local body
if body=$(curl -sf --max-time 10 \
-H "Authorization: Bearer ${API_TOKEN}" \
--retry "$(( MAX_RETRIES - attempt ))" \
--retry-delay "${wait}" \
--retry-connrefused \
"${URL}"); then
echo "$body" | jq -r '.rows | length'
return 0
fi
local code=$?
if (( code == 22 )); then
# 429/5xx:优先读服务端的 Retry-After
local retry_after
retry_after=$(curl -s -o /dev/null -D - "${URL}" \
| awk -F': ' 'tolower($1)=="retry-after" {gsub(/\r/, "", $2); print $2}')
if [[ "${retry_after}" =~ ^[0-9]+$ ]]; then
wait=$(( retry_after + 1 ))
fi
fi
(( attempt++ )) || true
(( attempt < MAX_RETRIES )) || break
echo "第 ${attempt} 次失败,${wait}s 后重试" >&2
sleep "${wait}"
wait=$(( wait * 2 )) # 指数退避
done
echo "Error: 重试耗尽仍无法获取报告" >&2
return 1
}
: "${API_TOKEN:?环境变量 API_TOKEN 未设置}"
fetch_report
How 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 readonly and sleep, chained through 7 pipes so each stage’s output feeds the next.
A helper function (fetch_report) keeps the repeated logic out of the main flow.
Watch out for
- The pipeline is 7 stages deep — when it misbehaves, split the pipe and test the stages separately.
Statements that carry the weight
while (( attempt < MAX_RETRIES )); do
local body
if body=$(curl -sf --max-time 10 \
-H "Authorization: Bearer ${API_TOKEN}" \
--retry "$(( MAX_RETRIES - attempt ))" \
--retry-delay "${wait}" \
--retry-connrefused \
"${URL}"); then
echo "$body" | jq -r '.rows | length'
retry_after=$(curl -s -o /dev/null -D - "${URL}" \
| awk -F': ' 'tolower($1)=="retry-after" {gsub(/\r/, "", $2); print $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.cURL to fetch ConverterTranslate a curl command into equivalent JavaScript fetch() code, handling the request method, headers, JSON or raw body, and basic auth.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.
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?
- `readonly`, `sleep` 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.