check multiple ports using netcat nc

0

I'm using the follow to wait till a port opens.

while ! nc -z 127.0.0.1 8080; do sleep 0.1; done

how can the above be modified to check multiple ports. So the script should stop only when all ports are occupied, e.g. 8080, 8081, and 8082.

Abhishek Thakur

Posted 2018-06-07T08:33:30.437

Reputation: 101

Answers

0

You need to run nc separately for each port:

while ! (nc -z 127.0.0.1 8080 && nc -z 127.0.0.1 8081 && nc -z 127.0.0.1 8082)
    do sleep 0.1
done

(split across multiple lines for readability)

This uses a shell subshell with a list of commands with a logical "and" && operator; the second nc command is only run if the first one succeeded, etc.; once all nc commands are successful, the exit status of the subshell is true, this is negated by the ! and the while loop terminates.

wurtel

Posted 2018-06-07T08:33:30.437

Reputation: 1 359