Created
February 15, 2026 21:03
-
-
Save brandonhimpfen/f057ea110f27198d47d512b3bf947f65 to your computer and use it in GitHub Desktop.
Bash retry helper to retry a command N times with delay and optional exponential backoff (strict-mode friendly).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # ----------------------------------------------------------------------------- | |
| # Bash retry helper | |
| # ----------------------------------------------------------------------------- | |
| # Usage: | |
| # retry <attempts> <delay_seconds> <command...> | |
| # | |
| # Example: | |
| # retry 5 2 curl -f https://example.com | |
| # | |
| # Optional: | |
| # Set RETRY_BACKOFF=1 to enable exponential backoff. | |
| # ----------------------------------------------------------------------------- | |
| set -Eeuo pipefail | |
| retry() { | |
| local attempts="$1" | |
| local delay="$2" | |
| shift 2 | |
| local count=1 | |
| local exit_code=0 | |
| if [[ -z "${attempts:-}" || -z "${delay:-}" || $# -eq 0 ]]; then | |
| echo "Usage: retry <attempts> <delay_seconds> <command...>" >&2 | |
| return 2 | |
| fi | |
| while (( count <= attempts )); do | |
| echo "Attempt $count/$attempts: $*" | |
| if "$@"; then | |
| return 0 | |
| fi | |
| exit_code=$? | |
| if (( count == attempts )); then | |
| echo "Command failed after $attempts attempts." >&2 | |
| return "$exit_code" | |
| fi | |
| echo "Command failed with exit code $exit_code. Retrying in ${delay}s..." >&2 | |
| sleep "$delay" | |
| if [[ "${RETRY_BACKOFF:-0}" -eq 1 ]]; then | |
| delay=$(( delay * 2 )) | |
| fi | |
| ((count++)) | |
| done | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Example usage (uncomment to test) | |
| # --------------------------------------------------------------------------- | |
| # retry 5 1 ls /nonexistent | |
| # RETRY_BACKOFF=1 retry 5 1 curl -f https://example.com |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment