setevoy
setevoy

Reputation: 4662

bash: using function's exit code in conditional expressions

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

Upvotes: 0

Views: 104

Answers (1)

odradek
odradek

Reputation: 1001

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

Upvotes: 1

Related Questions