Retry With Exponential Backoff

Retry a shell command with exponential backoff and a bounded attempt count, failing loudly when exhausted.

BashResilience

Code

bashsnippet
21 lines
#!/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/health

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 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

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.