Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash -eu
- # The parentheses inside the {} is to scope the exported variables inside a subshell in the function
- until_it_works(){(
- export cmd="$1"
- export on_error="${2:-}"
- export max_tries="${3:-10}"
- export tries=1
- until [[ $tries -ge $max_tries || $(exit ${exit_status:-1}) ]]; do
- exit_status=0
- bash -euc "$cmd" || exit_status=$?
- if $(exit $exit_status); then break; fi
- echo "Try #$tries of $max_tries failed with status $exit_status."
- bash -c "$on_error"
- ((++tries))
- done
- if ! $(exit $exit_status); then echo "Try #$tries of $max_tries failed with status $exit_status.".; fi
- return $exit_status
- )}
- tests=0
- # simple success
- ((++tests)); echo -e "\n""Beginning test $tests"
- until_it_works "true" "sleep 1"
- echo test $tests returned $?
- # simple failure
- ((++tests)); echo -e "\n""Beginning test $tests"
- set +e
- until_it_works "false foo" "" 4
- echo test $tests returned $?
- set -e
- # delayed success and using exported variables in the script
- ((++tests)); echo -e "\n""Beginning test $tests"
- until_it_works 'echo tries:$tries; [[ $tries -ge 2 ]];' 'date; sleep 1' 5
- echo test $tests returned $?
- # Get rid of the wrapper parentheses and you'll get a different result
- [[ -n ${tries:-} ]] && echo tries carried over and is $tries || echo tries did not carry over
- # vim: ts=2 sts=2 sw=2 cul
Add Comment
Please, Sign In to add comment