Curl Retry With JSON Response Parsing
Poll a flaky JSON endpoint with curl retry flags, fail fast on HTTP errors, and extract fields with jq without leaving the pipeline.
Code
#!/usr/bin/env bash
set -euo pipefail
readonly URL="${1:?endpoint required}"
fetch_status() {
curl --silent --show-error --fail \
--retry 4 --retry-delay 1 --retry-all-errors \
--max-time 10 \
--header 'Accept: application/json' \
"${URL}"
}
payload="$(fetch_status)"
# jq 一次遍历产出两个字段;-r 去掉引号便于直接赋值
status="$(jq -r '.status' <<< "${payload}")"
version="$(jq -r '.version // "unknown"' <<< "${payload}")"
echo "status=${status} version=${version}"
# 数组遍历:每个元素取两个字段拼行
jq -r '.checks[]? | "\(.name): \(.ok)"' <<< "${payload}"What the code does
set -euo pipefail removes the shell’s usual optimism — errors abort, empty variables abort, hidden pipeline failures abort.
The work is delegated to readonly, curl and jq, chained through 1 pipe so each stage’s output feeds the next.
A helper function (fetch_status) keeps the repeated logic out of the main flow.
Statements that decide the outcome
payload="$(fetch_status)"
status="$(jq -r '.status' <<< "${payload}")"
version="$(jq -r '.version // "unknown"' <<< "${payload}")"
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.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.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.
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`, `curl`, `jq` 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.