Skip to content

Instantly share code, notes, and snippets.

@rm-you
Last active April 24, 2019 18:55
Show Gist options
  • Save rm-you/56b2a4354b72b1bf142854a099d1d9ed to your computer and use it in GitHub Desktop.
Save rm-you/56b2a4354b72b1bf142854a099d1d9ed to your computer and use it in GitHub Desktop.
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