Skip to content

Instantly share code, notes, and snippets.

@jauderho
Last active April 1, 2022 21:14
Show Gist options
  • Save jauderho/fac23f45196860a3a7f4413ff139f859 to your computer and use it in GitHub Desktop.
Save jauderho/fac23f45196860a3a7f4413ff139f859 to your computer and use it in GitHub Desktop.
Retry Git push with backoff
#!/bin/bash
# Retries a command a with backoff.
#
# The retry count is given by ATTEMPTS (default 100), the
# initial backoff timeout is given by TIMEOUT in seconds
# (default 5.)
#
# Successive backoffs increase the timeout by ~33%.
#
# Beware of set -e killing your whole script!
function try_till_success {
local max_attempts=${ATTEMPTS-100}
local timeout=${TIMEOUT-5}
local attempt=0
local exitCode=0
until [[ $attempt -ge $max_attempts ]]
do
"$@"
exitCode=$?
if [[ $exitCode == 0 ]]
then
break
fi
echo "Failure! Retrying in $timeout.." 1>&2
sleep "$timeout"
attempt=$(( attempt + 1 ))
timeout=$(( timeout * 40 / 30 ))
done
if [[ $exitCode != 0 ]]
then
echo "You've failed me for the last time! ($*)" 1>&2
fi
return $exitCode
}
@warmlogic
Copy link

Thanks for sharing this. Just want to note that this didn't work for me (always exits after 2 attempts), but changing line 16 to the following does work: until [[ $attempt -ge $max_attempts ]]

@jauderho
Copy link
Author

jauderho commented Apr 1, 2022

To give credit where it is due, this gist came from https://news.ycombinator.com/item?id=30713151

Thanks for trying it out as I had not actually tested it for myself.

Fixed the snippet and ran it through shellcheck for good measure.

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