0

I'm trying to use redirection (learning purposes) and was wondering how i can reference this array so i can iterate through it. i know there are other ways but i'm trying to stick with redirection.

#!/bin/bash
count=0
for i in  10.10.{0..255}.{0..255}
do
ips[$count]=$i
let count+=1
done

echo -e "$count = count\n" #test code for amount

#problem code: trying to feed the array to the while loop via redirection
while read $element; do
echo -en "$element\n"
done < ${ips[@]}

1 Answer 1

1

Use <<< to redirect a string (vice < which accepts file names). This is not the most natural way to loop over an array: you also have to use read -d' ' to split on spaces instead of on newlines.

while read -d' ' $element; do
    echo -en "$element\n"
done <<< "${ips[@]}"

For comparison, the more idiomatic way of looping over an array would be:

for ip in "${ips[@]}"; do
    echo -en "$ip\n"
done

Also, for what it's worth, you could simplify the first loop to:

for i in 10.10.{0..255}.{0..255}; do
    ips+=($i)
done

Or even simply:

ips=(10.10.{0..255}.{0..255})
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the clarification. that makes sense instead of iterating through the array to get a count. one more question about references, can you explain what's going on in this statement (total break down) like what exactly does $(something) do? does the hashsign reference something? thanks. ${#ips[@]}
The hash sign gets the number of items in the array. ${ips[@]} is the list of addresses and ${#ips[@]} is the count.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.