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.

BashResilience

Code

snippet
#!/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

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.