How to wait for an open port with netcat?

You can't set netcat to wait until some port is open, so you have to add part for waiting before next check is made. Try this:

#!/bin/bash

echo "Waiting jenkins to launch on 8080..."

while ! nc -z localhost 8080; do   
  sleep 0.1 # wait for 1/10 of the second before check again
done

echo "Jenkins launched"

I suggest the following one liners:

## netcat version:
timeout 22 sh -c 'until nc -z $0 $1; do sleep 1; done' stackoverflow.com 443

## pure bash version:
timeout 22 bash -c 'until printf "" 2>>/dev/null >>/dev/tcp/$0/$1; do sleep 1; done' stackoverflow.com 443

Both commands exit as soon as connection is established, trying every second for up to 22 seconds.

Note that thanks to timeout command exit code is 0 when port is accessible otherwise 124 (if no connection established within given time).

Tags:

Shell

Bash

Netcat