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?
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.
possible by while loop
#!/bin/bash
declare -a arr=('1:one' '2:two' '3:three');
len=${#arr[@]}
i=0
while [ $i -lt $len ]; do
echo "${arr[$i]}"
let i++
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With