I have a netcat installed on my local machine and a service running on port 25565. Using the command:
nc 127.0.0.1 25565 < /dev/null; echo $?
Netcat checks if the port is open and returns a 0 if it open, and a 1 if it closed.
I am trying to write a bash script to loop endlessly and execute the above command every second until the output from the command equals 0 (the port opens).
My current script just keeps endlessly looping "...", even after the port opens (the 1 becomes a 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?
A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code. Well-behaved UNIX commands, programs, and utilities return a 0 exit code upon successful completion, though there are some exceptions.
Exit Success: Exit Success is indicated by exit(0) statement which means successful termination of the program, i.e. program has been executed without any error or interrupt.
In bash for, while, and until are three loop constructs. While each loop differs syntactically and functionally their purpose is to iterate over a block of code when a certain expression is evaluated. Until loop is used to execute a block of code until the expression is evaluated to be false.
Keep it Simple
until nc -z 127.0.0.1 25565 do echo ... sleep 1 done
Just let the shell deal with the exit status implicitly
The shell can deal with the exit status (recorded in $?
) in two ways, explicit, and implicit.
Explicit: status=$?
, which allows for further processing.
Implicit:
For every statement, in your mind, add the word "succeeds" to the command, and then add if
, until
or while
constructs around them, until the phrase makes sense.
until nc
succeeds; do ...; done
The -z
option will stop nc
from reading stdin, so there's no need for the < /dev/null
redirect.
You could try something like
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!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With