Retry a shell command with backoff
Re-run a flaky command a few times with increasing delays and a clear failure exit code.
- Bash
- GreenSnippets
- MIT
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
retry 5 2 curl --fail --silent --show-error https://example.com/healthHow 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.
Related snippets
- PHP Tested
Retry a callable with exponential backoff in PHP
Re-run flaky operations with growing delays and jitter, only for chosen exception types.
- JavaScript Tested
Send requests with an idempotency key
Make POST requests safe to retry by sending a unique Idempotency-Key that the server can de-duplicate.
- Bash
Clean up temporary files with trap
Create a temp directory and guarantee it is removed when the script exits, fails or is interrupted.
- Python Tested
Write a file atomically
Write to a temporary file and rename it into place so readers never see a half-written file.

