Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

shell - Bash for loop syntax

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...