Last active
November 3, 2020 10:38
-
-
Save carymrobbins/3c8a7a1a92c67a2a6709 to your computer and use it in GitHub Desktop.
Retry a bash command until successful.
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
#!/bin/bash | |
if [ "$1" == "-h" ] || [ "$1" == "--help" ] || [ "$1" == "" ]; then | |
echo "Usage: $(basename $0) n command" | |
echo "Execute command n times or until it succeeds (exit code 0)." | |
exit $([ $1 ] || echo 1) | |
fi | |
control_c() { | |
echo "$(tput setaf 1)Killing process per user request.$(tput sgr0)" | |
[ $EXIT_CODE ] && kill $EXIT_CODE | |
exit | |
} | |
trap control_c SIGINT | |
RETRY_MAX=$1 | |
shift | |
for i in $(seq 1 $RETRY_MAX); do | |
[ "$i" != "1" ] && echo "$(tput setaf 3)Retrying (attempt #$i):" "$@" "$(tput sgr0)" | |
"$@" | |
EXIT_CODE=$? | |
[ "$EXIT_CODE" == "0" ] && break | |
echo "$(tput setaf 1)Command failed with code $EXIT_CODE.$(tput sgr0)" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment