What’s the difference between the two ways of iterating over a bash array?

  Kiến thức lập trình

Can you explain the difference between the following two methods of iterating over an array in bash?
They seem identical to me.

Method 1

arr=("element 1" "element 2" "element 3")
for i in $arr; do
  echo "-> $i"
done

Method 2

arr=("element 1" "element 2" "element 3")
for i in "${arr[@]}"; do
  echo "-> $i"
done

They both give the following output:

-> element 1
-> element 2
-> element 3

I couldn’t find any documentation that compares the two methods, specifically in regards to arrays.

3

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT