retry_failed.sh 891 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. #
  4. # Retries a command RETRY_ATTEMPTS times in case of failure
  5. #
  6. # Inspired by https://stackoverflow.com/a/8351489
  7. #
  8. max_attempts=${RETRY_ATTEMPTS-3}
  9. RETRY_TIMEWAIT=${RETRY_TIMEWAIT-1}
  10. attempt=1
  11. exitCode=0
  12. whole_start=$(date +%s)
  13. attempt_start=whole_start
  14. while true; do
  15. if "$@" ; then
  16. exitCode=0
  17. break
  18. else
  19. exitCode=$?
  20. fi
  21. if (( $attempt >= $max_attempts )) ; then
  22. break
  23. fi
  24. echo "Failed! ("$@") Spent time $(( $(date '+%s') - ${attempt_start} )) sec. Retrying in ${RETRY_TIMEWAIT}..." 1>&2
  25. sleep $RETRY_TIMEWAIT
  26. attempt=$(( attempt + 1 ))
  27. RETRY_TIMEWAIT=$(( RETRY_TIMEWAIT * 2 ))
  28. attempt_start=$(date +%s)
  29. done
  30. if [[ $exitCode != 0 ]] ; then
  31. echo -n "Totally failed! ("$@")" 1>&2
  32. else
  33. echo -n "Done ("$@")" 1>&2
  34. fi
  35. echo " Spent time $(( $(date '+%s') - ${whole_start} )) sec in total" 1>&2
  36. exit $exitCode