7

I wrote in the terminal:

arr=(1 2 3)
for x in $arr; do
 echo $x
done

and it just prints '1'. Why doesn't it print 1 2 3 ?

Mano Mini
  • 607
  • 4
  • 15

2 Answers2

4

Change

for x in $arr; do

to

for x in "${arr[@]}"; do
user000001
  • 32,226
  • 12
  • 81
  • 108
1

To expand to all the elements of an array, use "${arr[@]}"

for x in "${arr[@]}"; do

When you use the array name as an ordinary variable, without indexing it, it expands to the first element.

Barmar
  • 741,623
  • 53
  • 500
  • 612