Retry a Bash command with timeout
One line and shortest, and maybe the best approach:
timeout 12h bash -c 'until ssh root@mynewvm; do sleep 10; done'
Credited by http://jeromebelleman.gitlab.io/posts/devops/until/
retry fuction is from:
http://fahdshariff.blogspot.com/2014/02/retrying-commands-in-shell-scripts.html
#!/bin/bash# Retries a command on failure.# $1 - the max number of attempts# $2... - the command to runretry() { local -r -i max_attempts="$1"; shift local -r cmd="$@" local -i attempt_num=1 until $cmd do if (( attempt_num == max_attempts )) then echo "Attempt $attempt_num failed and there are no more attempts left!" return 1 else echo "Attempt $attempt_num failed! Trying again in $attempt_num seconds..." sleep $(( attempt_num++ )) fi done}# example usage:retry 5 ls -ltr foo
if you want to retry an function in your script, you should do like this:
# example usage:foo(){ #whatever you want do.}declare -fxr fooretry 3 timeout 60 bash -ce 'foo'