Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Loop until command exit status equals 0

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?

like image 378
Snaacky Avatar asked Feb 24 '14 08:02

Snaacky


People also ask

What does exit code 0 mean in bash?

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.

What does an exit status of 0 mean?

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.

Does bash do until loop?

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.


2 Answers

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.

like image 73
Henk Langeveld Avatar answered Sep 20 '22 12:09

Henk Langeveld


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!" 
like image 31
Lee Duhem Avatar answered Sep 19 '22 12:09

Lee Duhem