Skip to content

Instantly share code, notes, and snippets.

@florianleibert
Created November 2, 2012 08:40
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save florianleibert/3999522 to your computer and use it in GitHub Desktop.
Save florianleibert/3999522 to your computer and use it in GitHub Desktop.
Retry logic in bash (for ssh / scp)
#!/bin/bash
set -o nounset
set -o errexit
set -o pipefail
declare -r max=4
declare i=0
function wrap() {
local cmd=$1 ; shift
retry $cmd "$@"
set -o errexit
}
function retry() {
set +o errexit
local cmd=$1 ; shift
$cmd "$@"
if [ $? -ne 0 -a $i -lt $max ] ; then
i=$(($i+1))
echo "Retrying"
sleep $((1+$i*$i*5))
retry $cmd "$@"
fi
}
wrap "$@"
@txominpelu
Copy link

It's great. Thanks @florianleibert!

The only problem that I had is that I wanted the exit status of the command to be different to zero when the retry fails. I've forked the gist and added this modification if you want to have a look.

https://gist.github.com/txominpelu/a8e886cf55e2c26d55c8

@leezer3
Copy link

leezer3 commented Mar 20, 2017

Useful little script.

I've made changes based upon both of the above, so if it fails with Code 6 initially (missing local file), it'll not continue retrying, and it'll similarly pass out any other non-zero failure codes after the appropriate retry length.

https://gist.github.com/leezer3/7f5add40ddb7b16654d2378e292bb28b

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