Skip to content

Instantly share code, notes, and snippets.

@regeda
Created January 12, 2021 10:10
Show Gist options
  • Save regeda/2847dc21ead224d92cdc5437e3ba87cd to your computer and use it in GitHub Desktop.
Save regeda/2847dc21ead224d92cdc5437e3ba87cd to your computer and use it in GitHub Desktop.
Backoff in Bash
function backoff_delay {
local -r -i factor=${BACKOFF_FACTOR-2}
local -i min=$(($1*$factor))
local -r -i max=$2
if [[ $max < $min ]]; then
min=$max
fi
echo $min
}
function with_backoff {
local -r -i max_attempts=${BACKOFF_MAX_ATTEMPTS-3}
local -i attempts=0
local -r -i max_delay=${BACKOFF_MAX_DELAY-30}
local -i delay=1
local exit_code=1
while [[ $((attempts++)) < $max_attempts ]]; do
"$@" && return 0
exit_code=$?
sleep $delay
delay=$(backoff_delay $delay $max_delay)
done
return $exit_code
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment