1

I am working on create a Bash script for my job that iterates through an array of IP addresses, and uses NC to scan for open ports on each of those IP addresses. If I were to use the NC command by itself and manually type out the command for each IP address, then it will work but that is not a good way to do it. However, I run into an error when I use an array with all of the IP addresses in it. Here is an example of my code (using IP addresses of Google and Microsoft for examples and privacy):

#!/bin/bash
IP_Addresses=(
172.217.6.142
191.239.213.197
)
FILE_Name=(
"google"
"microsoft"
)
for i in "${IP_Addresses[@]}"
do
    nc -w2 -zv4 ${IP_Addresses[@]} 1-100 > "${FILE_Name[$i]}".log 2>&1
done

The error I get from this example (which is similar to the example I get from the actual script) is this:

./testPorts.sh: line 14: 172.217.6.142: syntax error: invalid arithmetic operator (error token is ".217.6.142")
./testPorts.sh: line 14: 191.239.213.197: syntax error: invalid arithmetic operator (error token is ".239.213.197")

I had put the code in a file called testPorts.sh, made it executable and ran it from the terminal. And this is what I got. Line 14 is the line with the NC command. Does anybody know what I am doing wrong here, and if so, how do I fix it?

I have tried putting the IP addresses in quotes, but with the same error. If the IP addresses in the array are wrapped in quotes and/or the variable ${IP_Addresses[@]} are wrapped in quotes, I get the same error.

0

1 Answer 1

1

You appear to want to iterate over the indices of the two arrays - which you can do using indirection

#!/bin/bash
IP_Addresses=(
172.217.6.142
191.239.213.197
)
FILE_Name=(
"google"
"microsoft"
)
for i in "${!IP_Addresses[@]}"
do
    nc -w2 -zv4  "${IP_Addresses[$i]}" 1-100 > "${FILE_Name[$i]}".log 2>&1
done

Also be consistent about your variable names (FILE_Name versus FILE_NAME) and get into the habit of quoting variable expansions.

4
  • Thanks for the tips. I had tried using $i instead of @ in the NC command, but I get the same error but only for the first item in the array Mar 24, 2018 at 1:15
  • The issue, as it appears to me is that it is trying to parse the ip address as a number, yet the terminal doesn't support numbers with that many decimals as a floating number Mar 24, 2018 at 1:16
  • @ChristianSirolli did you remember to change the loop variable to indirect ${!IP_Addresses[@]} as I have shown rather than ${IP_Addresses[@]}? Mar 24, 2018 at 1:20
  • Don't know why I didn't see that difference. That seemed to work Mar 24, 2018 at 1:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .