Created
April 11, 2018 05:26
-
-
Save askoufis/0da8502b5f1df4d067502273876fcd07 to your computer and use it in GitHub Desktop.
Bash retry function with exponential backoff
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
#!/bin/bash | |
# Retry a command with exponential backoff | |
function retry { | |
local maxAttempts=$1 | |
local secondsDelay=1 | |
local attemptCount=1 | |
local output= | |
shift 1 | |
while [ $attemptCount -le $maxAttempts ]; do | |
output=$("$@") | |
local status=$? | |
if [ $status -eq 0 ]; then | |
break | |
fi | |
if [ $attemptCount -lt $maxAttempts ]; then | |
echo "Command [$@] failed after attempt $attemptCount of $maxAttempts. Retrying in $secondsDelay second(s)." >&2 | |
sleep $secondsDelay | |
elif [ $attemptCount -eq $maxAttempts ]; then | |
echo "Command [$@] failed after $attemptCount attempt(s)" >&2 | |
return $status; | |
fi | |
attemptCount=$(( $attemptCount + 1 )) | |
secondsDelay=$(( $secondsDelay * 2 )) | |
done | |
echo $output | |
} | |
retry 1 myfunc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is what I invented lol