0

I have next code:

...
docker_test () {

        local masterip=$1
        nc -zv $masterip 2377
}
...
        until $(docker_test $masterip); do
           echo "First Master not initialized yet..."
           sleep 30
        done
...

The question is - is it correct approach in bash to use loops or if/else in a such way?

Another example could be:

if $(docker_test $masterip); then
    echo "Passed"
fi
4
  • What is the issue here, if your intention is run nc -zv.. until it is successful (returning a code 0) this looks fine Commented Mar 23, 2017 at 12:43
  • 1
    @Inian Thanks. Yes, it works. But I have doubts in exactly until $(funcname); then construction. Will be until [ "$(docker_test $masterip)" == "0" ] more correct way here? Or it can be safly simplified to the same code, as mine is? Commented Mar 23, 2017 at 12:46
  • 2
    @setevoy Do you want the standard output or the exit code of the function? If the latter, just drop the command substitution. until docker_test "$master_ip"; do. Otherwise, until [ "$(docker_test "$master_ip")" = 0 ] (=, not ==) is correct. Commented Mar 23, 2017 at 13:07
  • @chepner Exit code, yes. Thanks. Commented Mar 23, 2017 at 13:18

1 Answer 1

1

i wouldn't risk the chance of the script hanging indefinitely if there's a problem with master. i would do something like:

#!/bin/bash -eu

readonly TRIES = 5  # attempts before failing
readonly SLEEP = 30  # sleep in seconds

for try in $(seq 1 $TRIES); do
    if docker_test "$master_ip"; then
        echo "Passed"
        break
    else
        if [ $try -eq $TRIES ]; then
            echo "Failed"
            exit 1  # or whatever you need
        fi
        echo "Retrying. Try $try of $TRIES"
        sleep $SLEEP
    fi
done
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.