Retry a command with exponential backoff
Network calls fail for a second and then work fine. A script shouldn’t die over that. This wraps any command, retrying with a doubling delay.
# retry — run a command up to N times with exponential backoff.
# Usage: retry 5 curl -sf https://example.com
retry() {
local max="$1"; shift
local n=1 delay=1
until "$@"; do
if (( n >= max )); then
echo "retry: '$*' failed after $max attempts" >&2
return 1
fi
echo "retry: attempt $n failed; sleeping ${delay}s" >&2
sleep "$delay"
(( n++, delay *= 2 ))
done
}
It returns the command’s success once it passes, or 1 after exhausting the attempts — so it drops straight into a set -e script:
retry 5 curl -sfO https://example.com/big-file.tar.gz
Delays go 1s, 2s, 4s, 8s… — five attempts span about 15s of waiting, enough to ride out most blips without hanging forever.