Cocoa Puffs Cocoa Puffs - 6 months ago 17
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.

#!/bin/bash

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

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
1:one
2:two
3:three

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.

Comments