Skip to content

Instantly share code, notes, and snippets.

@sonots

sonots/retry.sh

Last active Dec 24, 2019
Embed
What would you like to do?
#!/usr/bin/env bash
PROGNAME=$(basename $0)
function usage() {
echo "Usage: $PROGNAME [-c MAX_RETRY] [-s INTERVAL_SEC] -- COMMAND" 1>&2
echo " Retry a command if failed" 1>&2
echo "" 1>&2
echo "Options:" 1>&2
echo " -h, --help Show this message" 1>&2
echo " -c MAX_RETRY Number of retries (default: 3)" 1>&2
echo " -s INTERVAL_SEC Interval to retry in seconds (default: 1)" 1>&2
}
MAX_RETRY=3
INTERVAL_SEC=1
while [ ${#} -gt 0 ]
do
case $1 in
'-h'|'--help' )
usage
exit 0
;;
'-c' )
MAX_RETRY="$2"
shift 2
;;
'-s' )
INTERVAL_SEC="$2"
shift 2
;;
'--' )
shift
break
;;
*)
usage
exit 1
break
;;
esac
done
RETRY_COUNT=0
until [ $RETRY_COUNT -ge $MAX_RETRY ]; do
$@
if [ $? -eq 0 ]; then exit 0; fi
let ++RETRY_COUNT
sleep $INTERVAL_SEC
echo "[RETRY $RETRY_COUNT] Failed to execute, retry '$@'" 1>&2
done
echo "No success to execute '$@'" 1>&2
exit 1
@sonots

This comment has been minimized.

Copy link
Owner Author

@sonots sonots commented Dec 21, 2019

$ ./retry.sh -c 3 -s 1 -- ls /hoge
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.