Last active
April 24, 2019 18:55
-
-
Save rm-you/56b2a4354b72b1bf142854a099d1d9ed to your computer and use it in GitHub Desktop.
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
function try_x_times () { | |
command="${1:-echo 'No command given.'}" | |
tries="${2:-10}" | |
delay="${3:-2}" | |
# Preserve bash -e mode | |
if [[ $SHELLOPTS =~ 'errexit' ]]; then | |
errexit="true" | |
set +e | |
else | |
errexit="false" | |
fi | |
until [[ ${tries} -le 0 ]]; do | |
echo "Attempting to run command (${tries} left): \`${command}\`" | |
eval ${command} | |
retval=$? | |
if [[ ${retval} -eq 0 ]]; then | |
[[ ${errexit} = "true" ]] && set -e | |
return 0 | |
fi | |
let tries-=1 | |
sleep ${delay} | |
done | |
[[ ${errexit} = "true" ]] && set -e | |
return ${retval} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment