16

Here's what I'm trying. What I want is the last echo to say "one two three four test1..." as it loops. It's not working; read line is coming up empty. Is there something subtle here or is this just not going to work?

array=( one two three )
echo ${array[@]}
#one two three
array=( ${array[@]} four )
echo ${array[@]}
#one two three four


while read line; do
        array=( ${array[@]} $line )
        echo ${array[@]}
done < <( echo <<EOM
test1
test2
test3
test4
EOM
)
Jim Counts
  • 12,535
  • 9
  • 45
  • 63
Shawn J. Goff
  • 4,635
  • 8
  • 34
  • 38

3 Answers3

36

I would normally write:

while read line
do
    array=( ${array[@]} $line )
    echo ${array[@]}
done <<EOM
test1
test2
test3
test4
EOM

Or, even more likely:

cat <<EOF |
test1
test2
test3
test4
EOF

while read line
do
    array=( ${array[@]} $line )
    echo ${array[@]}
done

(Note that the version with a pipe will not necessarily be suitable in Bash. The Bourne shell would run the while loop in the current shell, but Bash runs it in a subshell — at least by default. In the Bourne shell, the assignments made in the loop would be available in the main shell after the loop; in Bash, they are not. The first version always sets the array variable so it is available for use after the loop.)

You could also use:

array+=( $line )

to add to the array.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
5

replace

done < <( echo <<EOM

with

done < <(cat << EOM

Worked for me.

sha
  • 17,824
  • 5
  • 63
  • 98
1

You can put the command in front of while instead:

(echo <<EOM
test1
test2
test3
test4
EOM
) | while read line; do
        array=( ${array[@]} $line )
        echo ${array[@]}
done
hlovdal
  • 26,565
  • 10
  • 94
  • 165