retry.sh 511 B

123456789101112131415161718192021222324252627
  1. #!/usr/bin/env bash
  2. function fail {
  3. echo $1 >&2
  4. exit 1
  5. }
  6. function retry {
  7. local n=1
  8. local max=3 # 3 retries before failure
  9. local delay=5 # delay between retries, 5 seconds
  10. while true; do
  11. echo "Running command '$@' with retry, attempt $n/$max"
  12. "$@" && break || {
  13. if [[ $n -lt $max ]]; then
  14. ((n++))
  15. sleep $delay;
  16. else
  17. fail "The command has failed after $n attempts."
  18. fi
  19. }
  20. done
  21. }
  22. if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  23. retry "$@"
  24. fi