Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Retry logic in bash (for ssh / scp)
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
echo "Retrying"
sleep $((1+$i*$i*5))
retry $cmd "$@"
wrap "$@"
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.

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.

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