0

I would like to check if I can connect to a port or not from within a bash script

Based on the answer to a similar question I tried running

nc -zvw10 <host> <port>

and check if the status code is 0/1

but many times it returns "Connection refused" and exits the script (there doesnt seem to be a return code)

I only want to exit the script if it returns a 0, which means a connection is made.

user2175783
  • 1,291
  • 1
  • 12
  • 28
  • The script ending indicates that you are using `set -e`; don't do that, or update your question to explain why you need it and what you have done to cope with the consequences. – tripleee Sep 26 '22 at 11:49

2 Answers2

1

You can redirect the output and error stream to /dev/null using nc -zvw10 <host> <port> &>/dev/null

Niraj Nandane
  • 1,318
  • 1
  • 13
  • 24
1

Use boolean operators:

#!/bin/bash
nc -zvw10 $1 $2 && exit 1 || echo "continue."
echo "It continues."

And on a closed port, it stops:

bash bar.sh localhost 2048
nc: connect to localhost port 2048 (tcp) failed: Connection refused
continue.
It continues.

So on open port:

bash bar.sh localhost 2049
Connection to localhost 2049 port [tcp/nfs] succeeded!