-
-
Save Graham42/1264680eaf839f4305d6c37381ec2a64 to your computer and use it in GitHub Desktop.
Bash retry function
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
# echo, but to stderr | |
function echoerr { | |
echo "$@" 1>&2; | |
} | |
# Retry a command up to a specific numer of times until it exits successfully, | |
# with exponential back off. | |
# | |
# $ retry 5 echo Hello | |
# Hello | |
# | |
# $ retry 5 false | |
# Retry 1/5 exited 1, retrying in 15 seconds... | |
# Retry 2/5 exited 1, retrying in 30 seconds... | |
# Retry 3/5 exited 1, retrying in 60 seconds... | |
# Retry 4/5 exited 1, retrying in 120 seconds... | |
# Retry 5/5 exited 1, no more retries left. | |
# | |
function retry { | |
local WAIT_MODIFIER=15 | |
local retries=$1 | |
shift | |
local count=0 | |
until "$@"; do | |
exit=$? | |
wait=$((2 ** $count * ${WAIT_MODIFIER:-1})) | |
count=$(($count + 1)) | |
if [ $count -lt $retries ]; then | |
echoerr "Retry $count/$retries exited $exit, retrying in $wait seconds..." | |
sleep $wait | |
else | |
echoerr "Retry $count/$retries exited $exit, no more retries left." | |
return $exit | |
fi | |
done | |
return 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment