Skip to content

Instantly share code, notes, and snippets.

@davenicoll
Last active January 20, 2023 19:35
Show Gist options
  • Save davenicoll/b49a16a70740659fbd2b49c3813e24e4 to your computer and use it in GitHub Desktop.
Save davenicoll/b49a16a70740659fbd2b49c3813e24e4 to your computer and use it in GitHub Desktop.
Bash retry with exponential backoff
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}
}
@davenicoll
Copy link
Author

davenicoll commented Jan 20, 2023

Usage: with_backoff curl http://kdjaskdjkasjda.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment