Bash: loop until the command completion status is 0

I have netcat installed on my local computer and a service running on port 25565. Using the command:

nc 127.0.0.1 25565 < /dev/null; echo $?

Netcat checks to see if the port is open and returns 0 if it is open, and 1 if it is closed.

I try to write a bash script loop endlessly, and execute this command every time until the output of the command is 0 (the port opens).

My current script just continues to endlessly loop "...", even after opening the port (1 becomes 0).

until [ "nc 127.0.0.1 25565 < /dev/null; echo $?" = "0" ]; do
         echo "..."
         sleep 1
     done
echo "The command output changed!"

What am I doing wrong here?

+7
source share
2 answers

Be more simple

until nc -z 127.0.0.1 25565
do
    echo ...
    sleep 1
done

Just let the shell implicitly deal with exit status

( $?) : .

: status=$? , .

:

, , "success" , if, until while , .

until nc ; do...; done ; do...; done


-z nc stdin, </dev/null.

+34

-

while true; do
    nc 127.0.0.1 25565 < /dev/null
    if [ $? -eq 0 ]; then
        break
    fi
    sleep 1
done
echo "The command output changed!"
+4

All Articles