Skip to content

Instantly share code, notes, and snippets.

@rainabba
Last active May 8, 2023 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rainabba/9b6bbcac087d46d1a1314825aee8b322 to your computer and use it in GitHub Desktop.
Save rainabba/9b6bbcac087d46d1a1314825aee8b322 to your computer and use it in GitHub Desktop.
Bash retry with exponential backoff

A 1-liner bash function to provide basic non-zero exit retry with exponential backoff:

Minified

function retry_backoff {local m=${ATTEMPTS:-5};local t=${TIMEOUT:-1};local a=0;local e=1;while (($a < $m));do "$@";e=$?;if (($e == 0)); then break;fi;echo "Failure! Retrying in $t.." 1>&2;sleep $t;((a++));t=$((t*2));done;if (($e != 0));then echo "Max attempts reached!" 1>&2;fi;return $e; }

Use

retry_backoff $YOUR_COMMAND # default of 5 retries, starting with 1 second timeout
ATTEMPTS=3 TIMEOUT=10 retry_backoff $YOUR_COMMAND # 3 attempts with a starting timeout of 10 seconds

Sample

$ ATTEMPTS=3 TIMEOUT=10 retry_backoff retry_backoff curl http://foobar.none
curl: (6) Could not resolve host: foobar.none
Failure! Retrying in 1..
curl: (6) Could not resolve host: foobar.none
Failure! Retrying in 2..
curl: (6) Could not resolve host: foobar.none
Failure! Retrying in 4..
curl: (6) Could not resolve host: foobar.none
Failure! Retrying in 8..
curl: (6) Could not resolve host: foobar.none
Failure! Retrying in 16..

Full code

function retry_backoff {
  local max_attempts=${ATTEMPTS:-5};
  local timeout=${TIMEOUT:-1};
  local attempts=0;
  local exitCode=1;

  while [ $attempts -lt $max_attempts ];
  do
    "$@";
    exitCode=$?;

    if [ $exitCode -eq 0 ]; then
      break;
    fi;

    echo "Failure! Retrying in $timeout.." 1>&2;
    sleep $timeout;
    attempts=$(( attempts + 1 ));
    timeout=$(( timeout * 2 ));
  done;

  if [ $exitCode -ne 0 ]; then
    echo "Max attempts reached!" 1>&2;
  fi;
  
  return $exitCode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment