0

I found strange problem in bash: pushing to array is not working when I use while read loop

Here is an example:

#!/bin/bash
LINES=$(cat <<EOF
line1
line2
line3
EOF
)
declare -a x
x+=("x0")
echo "$LINES" | while read line ; do
  echo "debug: $line"
  x+=("$line")
done
echo "${x[@]}"
echo "DONE"

echo "${x[@]}" shows only x0 but must be x0 line1 line2 line3

If I use while without read everything is ok:

#!/bin/bash
declare -a x
COUNTER=0
while [  $COUNTER -lt 10 ]; do
  let COUNTER=COUNTER+1
  x+=("$COUNTER")
done
echo "${x[@]}" # 1 2 3 4 5 6 7 8 9 10

Please help me to figure out what is the problem

My bash version is 5.0.17(1)-release (x86_64-pc-linux-gnu)

Paul Serikov
  • 2,550
  • 2
  • 21
  • 36

0 Answers0