Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 390
Cocoa Puffs Avatar asked Dec 10 '22 16:12

Cocoa Puffs


2 Answers

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.

like image 94
John1024 Avatar answered Dec 27 '22 03:12

John1024


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
like image 34
sumitya Avatar answered Dec 27 '22 04:12

sumitya