Retry a Command With Backoff

Retry a shell command that may fail transiently, waiting longer between attempts and reporting the last error when all tries are exhausted.

BashResilience

Code

snippet
#!/usr/bin/env bash
set -euo pipefail

retry() {
  local attempts="${1:?attempts required}"
  local delay="${2:?delay required}"
  shift 2
  local attempt=1
  while true; do
    if "$@"; then
      return 0
    fi
    if (( attempt >= attempts )); then
      echo "command failed after ${attempts} attempts: $*" >&2
      return 1
    fi
    echo "attempt ${attempt} failed, retrying in ${delay}s" >&2
    sleep "${delay}"
    delay=$(( delay * 2 ))
    attempt=$(( attempt + 1 ))
  done
}

retry 4 1 curl --fail --silent --show-error https://api.example.com/health