-
-
Save simonkowallik/12676d7e067a63f09eb03050d19ec7c5 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
# Retry a command with a fixed numer of times until it exits successfully, | |
# with exponential back off + 1. | |
# usage: | |
# $ source ./retry.sh | |
# $ retry echo "hello world" | |
# hello world | |
# $ retry false | |
# Retry 1/7: command exited with code 1, retrying in 2 seconds. Retrying... | |
# Retry 2/7: command exited with code 1, retrying in 3 seconds. Retrying... | |
# Retry 3/7: command exited with code 1, retrying in 5 seconds. Retrying... | |
# Retry 4/7: command exited with code 1, retrying in 9 seconds. Retrying... | |
# Retry 5/7: command exited with code 1, retrying in 17 seconds. Retrying... | |
# Retry 6/7: command exited with code 1, retrying in 33 seconds. Retrying... | |
# Retry 7/7: command exited with code 1, retrying in 65 seconds. Retrying... | |
# command exited with code 1, no more retries left. | |
# | |
function retry { | |
local retries=7 | |
local count=0 | |
until "$@"; do | |
exit=$? | |
wait=$((2 ** $count + 1)) | |
count=$(($count + 1)) | |
if [ $count -lt $(($retries + 1)) ]; then | |
echo -n "Retry $count/$retries: command exited with code $exit, retrying in $wait seconds. " | |
sleep $wait | |
echo "Retrying..." | |
else | |
echo "command exited with code $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