0

I need to read the following command outputs into an array, and then loop through that array within another command.

  1. File hosts contains 2 IP addresses:
    • 192.168.3.78
    • 192.168.3.79

should read the output of sed ":a;N;$!ba;s/\n/ /g" $hosts into array sednames
sednames=( $(sed ":a;N;$!ba;s/\n/ /g" $hosts) )

I then have another loop to read through static ports (does work, as the ports are defined in the script). I want to then run each IP through this command with each port

m is supposed to be the array of IP's i is the list of ports (which does work)

for m in "$sednames"  
do  
echo "m = $m"  
var=$(python -c "import socket; print(socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect_ex((\"$m\", $i)))")

The problem I am running into is that sednames and m only seems to contain the first ip, nothing more. Also, the python script barfs on the newline after .78, so that's the reasoning for the sed command to eliminate newlines to loop through each string in the array.

5
  • This is a problem with how you're iterating over the array, not with how you're reading into it. for m in "$sednames" ignores everything but the first element. Commented Jun 6, 2017 at 20:56
  • Use for m in "${sednames[@]}"; do ... Commented Jun 6, 2017 at 20:57
  • (that said, the way you're reading into the array is also an antipattern, but not for any reasons related to bugs you're hitting right now) Commented Jun 6, 2017 at 20:57
  • (See BashFAQ #5 on "loading lines from a file or stream" for the best-practices replacement for that code). Commented Jun 6, 2017 at 20:59
  • Thanks Charles, you were right. Instead of getting rid of the \n I just cut it off before using the value. Commented Jun 7, 2017 at 13:16

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.