-
-
Save mjlescano/d3cef76adaf9ad8448c0 to your computer and use it in GitHub Desktop.
Bash function for running a command, checking the return code, and re-trying it `x` times after `y` sleep seconds.
This file contains hidden or 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 | |
# Usage: | |
# retry <commands...> | |
# retry <retry times> <commands...> | |
# retry <retry times> <retry wait> <commands...> | |
if [[ $2 =~ ^-?[0-9]+$ ]]; then | |
cmd="${@:3}" | |
retry_times=$1 | |
retry_wait=$2 | |
elif [[ $1 =~ ^-?[0-9]+$ ]]; then | |
cmd="${@:2}" | |
retry_times=$1 | |
retry_wait=1 | |
else | |
cmd="$@" | |
retry_times=5 | |
retry_wait=1 | |
fi | |
c=0 | |
while [ $c -lt $((retry_times+1)) ]; do | |
c=$((c+1)) | |
echo "$(tput setaf 6)Executing \"$cmd\", try $c$(tput sgr0)" | |
$(echo $cmd) && echo "$(tput setaf 6)Done!$(tput sgr0)" && exit $? | |
if [ ! $c -eq $retry_times ]; then | |
echo "$(tput setaf 6)Command failed, will retry in $retry_wait secs$(tput sgr0)" | |
sleep $retry_wait | |
else | |
echo "$(tput setaf 6)Command failed, giving up.$(tput sgr0)" | |
exit 1 | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment