Skip to content
GreenSnippets

Retry a shell command with backoff

Re-run a flaky command a few times with increasing delays and a clear failure exit code.

Bash
retry() {
  local attempts="$1" delay="$2"
  shift 2
  local n=1
  until "$@"; do
    local status=$?
    if (( n >= attempts )); then
      echo "Command failed after $n attempts: $*" >&2
      return "$status"
    fi
    echo "Attempt $n failed (exit $status); retrying in ${delay}s…" >&2
    sleep "$delay"
    delay=$(( delay * 2 ))
    n=$(( n + 1 ))
  done
}

Example / expected output

Output
retry 5 2 curl --fail --silent --show-error https://example.com/health

How it works

Useful in CI and deploy scripts for network calls that fail occasionally. The function runs the command passed as arguments, doubles the delay after each failure and returns the last exit status when attempts are exhausted. Only retry commands that are safe to repeat.

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.