Skip to content

Retry a command

Re-run a command with exponential backoff until it succeeds or hits a limit.

18th August 2026

retry() {
  local attempts="${1:-5}"
  local delay="${2:-1}"
  shift 2
  local n=1
  until "$@"; do
    if (( n >= attempts )); then
      return 1
    fi
    sleep "${delay}"
    delay=$((delay * 2))
    n=$((n + 1))
  done
}

Caveats

Not for commands that are not idempotent.