Skip to content

Instantly share code, notes, and snippets.

@mjlescano
Forked from dansimau/gist:842415
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjlescano/d3cef76adaf9ad8448c0 to your computer and use it in GitHub Desktop.
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.
#!/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