0

I wrote this simple script to check whether some of the specific ports are open or not.

#!/bin/bash    
prt=(8080,22,53)
for i in "${prt[@]}"
do
  nc -vz 127.0.0.1 $i
  if [ $? -eq 0 ]; then  
    echo "succeeded"
    echo $i
    break
  else
    echo "refused"
  fi
done

It should loop through the list of ports and print the first open port and then break from the loop. Except 8080 all other ports are open in my system and should in theory output succeeded 22. But instead of doing that this is the output its giving

nc: port number invalid: 8080,22,53
refused
  • 2
    When you have a shell problem, a good first step is to cut and paste your code into shellcheck.net. In this case, as in many cases, it would have solved your problem quite quickly. – John1024 Feb 7 '18 at 18:36
3

man bash says:

Arrays are assigned to using compound assignments of the form name=(value1 ... valuen), where each value is of the form [subscript]=string.

So to populate your array, you should rather do:

prt=(8080 22 53)

I would do the task as follows:

#!/bin/bash
prt=(8080 22 53)
for i in "${prt[@]}"; do
  if nc -vz 127.0.0.1 $i; then
    echo -e succeeded\\n$i
    break
  else
    echo refused
  fi
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.