Skip to content

Instantly share code, notes, and snippets.

@sonots
Last active December 9, 2020 01:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sonots/e6954ed0e96124589e3d4021cb502625 to your computer and use it in GitHub Desktop.
Save sonots/e6954ed0e96124589e3d4021cb502625 to your computer and use it in GitHub Desktop.
#!/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
Copy link
Author

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