Guest User

Untitled

a guest
Nov 20th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #!/bin/bash -eu
  2.  
  3. # The parentheses inside the {} is to scope the exported variables inside a subshell in the function
  4. until_it_works(){(
  5. export cmd="$1"
  6. export on_error="${2:-}"
  7. export max_tries="${3:-10}"
  8.  
  9. export tries=1
  10. until [[ $tries -ge $max_tries || $(exit ${exit_status:-1}) ]]; do
  11. exit_status=0
  12. bash -euc "$cmd" || exit_status=$?
  13. if $(exit $exit_status); then break; fi
  14. echo "Try #$tries of $max_tries failed with status $exit_status."
  15. bash -c "$on_error"
  16. ((++tries))
  17. done
  18. if ! $(exit $exit_status); then echo "Try #$tries of $max_tries failed with status $exit_status.".; fi
  19. return $exit_status
  20. )}
  21.  
  22. tests=0
  23. # simple success
  24. ((++tests)); echo -e "\n""Beginning test $tests"
  25. until_it_works "true" "sleep 1"
  26. echo test $tests returned $?
  27.  
  28. # simple failure
  29. ((++tests)); echo -e "\n""Beginning test $tests"
  30. set +e
  31. until_it_works "false foo" "" 4
  32. echo test $tests returned $?
  33. set -e
  34.  
  35. # delayed success and using exported variables in the script
  36. ((++tests)); echo -e "\n""Beginning test $tests"
  37. until_it_works 'echo tries:$tries; [[ $tries -ge 2 ]];' 'date; sleep 1' 5
  38. echo test $tests returned $?
  39.  
  40. # Get rid of the wrapper parentheses and you'll get a different result
  41. [[ -n ${tries:-} ]] && echo tries carried over and is $tries || echo tries did not carry over
  42.  
  43. # vim: ts=2 sts=2 sw=2 cul
Add Comment
Please, Sign In to add comment