How to display nc return value in Linux shell script?

13,438

This small script should do the trick:

#!/bin/bash
SERVER=$1
PORT=$2
nc -z -v -G5 $SERVER $PORT &> /dev/null
result1=$?

#Do whatever you want

if [  "$result1" != 0 ]; then
  echo  port $PORT is closed on $SERVER
else
  echo port $PORT is open on $SERVER
fi

Usage:

./myscript.sh servername portnumber

For example:

./myscript www.google.com 80
www.google.com 80
port 80 is open on www.google.com

Depending on the version of nc you're using, you may need to adjust the -G to -w, so experiment and find which works best for you.

Share:
13,438
Alfred
Author by

Alfred

I am a Full Stack developer and a DevOps Engineer, who always to learn from, and contribute to, the technology community. I was a beginner in programming once. What all I had was pieces of scattered and crude knowledge (don't know if i can call it knowledge) then. Later, I joined for Master of Computer Applications in a college and there, I got a great teacher. It was her, who taught me when and where to use 'while' and 'for' loops even.What all knowledge I have now, and what all achievements I've made till now, is only because of her. Compared to her, I am ashes. Hats off my dear teacher Sonia Abraham, you are the best of your kind. Sonia Abraham is a professor of the Department of Computer Applications, M.A College of Engineering, Mahatma Gandhi University

Updated on June 28, 2022

Comments

  • Alfred
    Alfred almost 2 years

    I am using nc command in my Linux box like below to check if a port is listening;

    This displays success message:

    nc -z 192.168.0.2 9000
    

    This displays 0:

    echo $?
    

    I have combined it in a shell script .sh file like below;

    #!/bin/sh
    nc -z 192.168.0.2 9000
    echo $?
    

    This displays 1 instead of expected 0. Again, if I modify my script like below, it works;

    #!/bin/sh
    echo nc -z 192.168.0.2 9000
    echo $?
    

    But here the problem is, it displays success message on one like, then displays 0 in next line. I don't want success message, and I am expecting 0. What is wrong here and how can I fix this?