Bash for loop syntax

前提是你 提交于 2020-01-20 08:46:08

问题


I'm working on getting accustomed to shell scripting and ran across a behavior I found interesting and unexplained. In the following code the first for loop will execute correctly but the second will not.

declare letters=(a b c d e f g)
for i in {0..7}; do
  echo ${letters[i]}
done
for i in {0..${#letters[*]}}; do
  echo ${letters[i]}
done

The second for loop results in the following error:

syntax error: operand expected (error token is "{0..7}")

What confuses me is that ${#letters[*]} is clearly getting evaluated, correctly, to the number 7. But despite this the code fails even though we just saw that the same loop with {0..7} works perfectly fine.

What is the reason for this?

I am running OS X 10.12.2, GNU bash version 3.2.57.


回答1:


Brace expansion occurs before parameter expansion, so you can't use a variable as part of a range.

Expand the array into a list of values:

for letter in "${letters[@]}"; do
    echo "$letter"
done

Or, expand the indices of the array into a list:

for i in ${!letters[@]}; do 
    echo "${letters[i]}"
done

As mentioned in the comments (thanks), these two approaches also accommodate sparse arrays; you can't always assume that an array defines a value for every index between 0 and ${#letters[@]}.




回答2:


The bracket expansion happens before parameter expansion (see EXPANSIONS in man bash), therefore it works for literals only. In other words, you can't use brace expansion with variables.

You can use a C-style loop:

for ((i=0; i<${#letters[@]}; i++)) ; do
    echo ${letters[i]}
done

or an external command like seq:

for i in $(seq 1 ${#letters[@]}) ; do
    echo ${letters[i-1]}
done

But you usually don't need the indices, instead one loops over the elements themselves, see @TomFenech's answer below. He also shows another way of getting the list of indices.

Note that it should be {0..6}, not 7.



来源:https://stackoverflow.com/questions/42162615/bash-for-loop-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!