Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why for-in loop doesn't print what I want? [duplicate]

Tags:

bash

for-loop

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 ?

like image 276
Mano Mini Avatar asked Oct 15 '15 19:10

Mano Mini


2 Answers

Change

for x in $arr; do

to

for x in "${arr[@]}"; do
like image 200
user000001 Avatar answered Sep 24 '22 09:09

user000001


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.

like image 40
Barmar Avatar answered Sep 26 '22 09:09

Barmar