Skip to content

Instantly share code, notes, and snippets.

@askoufis
Created April 11, 2018 05:26
Show Gist options
  • Save askoufis/0da8502b5f1df4d067502273876fcd07 to your computer and use it in GitHub Desktop.
Save askoufis/0da8502b5f1df4d067502273876fcd07 to your computer and use it in GitHub Desktop.
Bash retry function with exponential backoff
#!/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
@norpol
Copy link

norpol commented Aug 4, 2022

Here is what I invented lol

for i in $(seq 4); do
    ! might-fail-or-not || break
    test "${i}" != "4" || { echo "Reached max attempts"; false; }
    sleep "${i}s"
done

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