Cocoa Puffs Cocoa Puffs - 2 years ago 170
Linux Question

while read bash array (not into)

I'm trying to use an array with

while read
, but the entire array is output at once.


declare -a arr=('1:one' '2:two' '3:three');

while read -e it ; do
echo $it
done <<< ${arr[@]}

It should output each value separately (but doesn't), so maybe while read isn't the hot ticket here?

Answer Source

For this case, it is easier to use a for loop:

$ declare -a arr=('1:one' '2:two' '3:three')
$ for it in "${arr[@]}"; do echo $it; done

The while read approach is very useful (a) When you want to read data from a file, and (b) when you want to read in a nul or newline separated string. In your case, however, you already have the data in a bash variable and the for loop is simpler.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download