Bash for loop syntax

前端 未结 2 387
孤独总比滥情好
孤独总比滥情好 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:05

    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.

提交回复
热议问题