Skip to content

Instantly share code, notes, and snippets.

@mason-splunk
Forked from sj26/LICENSE.md
Created December 5, 2019 23:17
Show Gist options
  • Select an option

  • Save mason-splunk/a7874f97a5b207363ed7f9496685e4f0 to your computer and use it in GitHub Desktop.

Select an option

Save mason-splunk/a7874f97a5b207363ed7f9496685e4f0 to your computer and use it in GitHub Desktop.

Revisions

  1. @sj26 sj26 created this gist Dec 8, 2016.
    32 changes: 32 additions & 0 deletions retry.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    # Retry a command up to a specific numer of times until it exits successfully,
    # with exponential back off.
    #
    # $ retry 5 echo Hello
    # Hello
    #
    # $ retry 5 false
    # Retry 1/5 exited 1, retrying in 1 seconds...
    # Retry 2/5 exited 1, retrying in 2 seconds...
    # Retry 3/5 exited 1, retrying in 4 seconds...
    # Retry 4/5 exited 1, retrying in 8 seconds...
    # Retry 5/5 exited 1, no more retries left.
    #
    function retry {
    local retries=$1
    shift

    local count=0
    until "$@"; do
    exit=$?
    wait=$((2 ** $count))
    count=$(($count + 1))
    if [ $count -lt $retries ]; then
    echo "Retry $count/$retries exited $exit, retrying in $wait seconds..."
    sleep $wait
    else
    echo "Retry $count/$retries exited $exit, no more retries left."
    return $exit
    fi
    done
    return 0
    }