Last active
January 20, 2023 19:35
-
-
Save davenicoll/b49a16a70740659fbd2b49c3813e24e4 to your computer and use it in GitHub Desktop.
Bash retry with exponential backoff
This file contains 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
function with_backoff { | |
local max_attempts=${ATTEMPTS-5} | |
local timeout=${TIMEOUT-1} | |
local attempt=1 | |
local exitCode=0 | |
while [[ ${attempt} -lt ${max_attempts} ]]; do | |
"$@" | |
exitCode=$? | |
if [[ ${exitCode} == 0 ]]; then | |
break | |
fi | |
echo "Retrying in ${timeout} seconds..." 1>&2 | |
sleep "${timeout}" | |
attempt=$((attempt + 1)) | |
timeout=$((timeout * 2)) | |
done | |
if [[ ${exitCode} != 0 ]]; then | |
echo "Failure after maximum number of retry attempts" 1>&2 | |
fi | |
return ${exitCode} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
with_backoff curl http://kdjaskdjkasjda.com