Skip to content

Instantly share code, notes, and snippets.

@simonkowallik
Forked from sj26/LICENSE.md
Last active March 11, 2021 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonkowallik/12676d7e067a63f09eb03050d19ec7c5 to your computer and use it in GitHub Desktop.
Save simonkowallik/12676d7e067a63f09eb03050d19ec7c5 to your computer and use it in GitHub Desktop.
Bash retry function
# 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