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.
Code
#!/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/healthHow the snippet works
Strict mode (set -euo pipefail) makes failures loud — an unset variable or a failing pipeline stage aborts the script instead of being swallowed.
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.
The key statements, annotated
while true; do
if "$@"; then
return 0
if (( attempt >= attempts )); then
echo "command failed after ${attempts} attempts: $*" >&2
delay=$(( delay * 2 ))
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.