Created
May 17, 2017 14:33
-
-
Save erkolson/e9f27061a29953aa23341cb392abd39f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env sh | |
usage() { | |
cat <<-EOM | |
USAGE: `basename $0` <max_retries> <command> [<param1> [<param2> [...] ] ] | |
Retry shell commands until they work or max retries has been reached. | |
Helpful in a long running automation pipeline where a single non-zero | |
return status can waste a lot of time. | |
[Everything is just terrible, maybe we can mask it and pretend not.] | |
Example: | |
retry.sh 10 apk --no-cache add tini | |
EOM | |
exit 1 | |
} | |
fail() { | |
echo $@ | |
exit 2 | |
} | |
if [ $# -lt 2 ] ; then | |
usage | |
fi | |
retries=$1 | |
shift | |
command=$@ | |
bin=$(echo $command | awk '{print $1}') | |
[ -x `which ${bin}` ] || fail "ERROR $bin is not executable for this user (maybe it doesn't exist?)" | |
echo "Running \`$command\` with $retries retries" | |
n=0 | |
while true | |
do | |
$command && break | |
n=$(expr $n + 1) | |
if [ $n -le $retries ] ; then | |
echo "Retry # $n" | |
else | |
fail "ERROR: Max retries. Unable to \`$command\`" | |
fi | |
sleep 5 | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment