Question

I have a script that starts 5 services on 4000-4004 ports. I want that script to be blocked till all of them are up. Following works for me.

while ! nc -vz localhost 4000; do sleep 1; done
while ! nc -vz localhost 4001; do sleep 1; done
while ! nc -vz localhost 4002; do sleep 1; done
while ! nc -vz localhost 4003; do sleep 1; done
while ! nc -vz localhost 4004; do sleep 1; done

The only problem with above is if say 4002 is still not up, it will keep on waiting for it while I have no information about 4003 & 4004.

What I would like to do is that run all of these in parallel somehow and print out status of each port. And only when all of them are up, it continues after that block else it blocks and prints out what ports are up and down.

(Optionally I need to add some timeout as well, but that should be doable once I get how to do the above.)

Thanks a lot.

Edit:

Following worked great for me:

$ parallel --timeout 300 -j0 'while ! nc -vz localhost {}; do sleep 10; done; echo {} is open' ::: {4000..4004} 5001 || { echo "One or more serves failed to start. Exiting.."; exit 1; }

Note: Make sure you run the following after installation. ref-link

$ sudo rm /etc/parallel/config
Was it helpful?

Solution 2

With GNU Parallel you can do:

parallel --timeout 30 -j0 'while ! nc -vz localhost {}; do sleep 1; done; echo {} is open' ::: {4000..4004}

10 seconds installation:

wget -O - pi.dk/3 | sh

Watch the intro video for a quick introduction: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

OTHER TIPS

Yep, commenter is right, do it in the background. But then you have to wait for the background stuff implicitly:

while ! nc -vz localhost 4000; do sleep 1; done & pid1=$!
while ! nc -vz localhost 4001; do sleep 1; done & pid2=$!
while ! nc -vz localhost 4002; do sleep 1; done & pid3=$!
while ! nc -vz localhost 4003; do sleep 1; done & pid4=$!
while ! nc -vz localhost 4004; do sleep 1; done & pid5=$!
wait $pid1
wait $pid2
wait $pid3
wait $pid4
wait $pid5

This way, all five processes are started in parallel in the background, then almost at once the first wait is started. This one waits until the first background process is finished, then the second wait is started; probably this won't have to wait for long because the second background process will probably finish around the same time as the first.

So, in theory, this will take about as long as the longest of the five processes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top