Bash for loop syntax

前端 未结 2 381
孤独总比滥情好
孤独总比滥情好 2020-12-22 04:31

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 co

2条回答
  •  执笔经年
    2020-12-22 05:01

    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[@]}.

提交回复
热议问题