Wait for open port before running command

There comes a time in every software engineer’s life, when they need to run a
command, but only after a port has been opened by a completely separate process.

Sure, you could sit around and wait for the port to open up before running your
command, but what’s the fun in that?

Plus, if it’s worth waiting around for, it’s worth attempting to automate.

Fortunately, it doesn’t take much to handle this type of scenario. With your
trusty netcat command and a bit of shell scripting, you can pull it off.

While this guide does rely on netcat, specifically the nc command, it’s not
a guide to how to install it. If you happen to be running Debian or Ubuntu, I
can help out there, as the netcat-traditional package will get you what you

All right, so we need to wait for a port to open, checking periodically in a
loop before running another command. Before we get into all of that, let’s talk
about using the nc command by itself to see if a port is open.

The nc command can accept an address and a port and report back the status if
the connection is refused:

% nc 3000
(UNKNOWN) [] 3000 (?) : Connection refused

If the port was open, the nc command would just sit there, as it’s actively
connected to the address.

To avoid this, you can use the -z argument, which tells nc to go into what
they call “zero-I/O mode”, which will exit, regardless if it connects or not.

% nc 3000 && echo 'This only runs if the port is open'

Fantastic, we could run this over and over until the port is open, or… we
could leverage until and sleep commands to check every second until the port
is open:

until nc -z 3000 do sleep 1 done && echo 'Port 3000 is now open!'

Moving in the right direction, if we wanted to really class things up, we could
add some additional echo statements to give us some additional feedback so
that we can tell it’s working:

echo -n 'Waiting for port 3000 to open...' 
  && until nc -z 3000 
  do sleep 1 && echo -n . done 
  && echo 'nPort 3000 is now open!'

Now we’ll see the ... continue to grow every second as nc is checking,
ultimately running the final command in the chain!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.