Bash for循环语法 [英] Bash for loop syntax
问题描述
declare letters =(a b c d e f g)
for i in {0..7};
echo $ {letters [i]}
完成
for {0 .. $ {#letters [*]}}做
echo $ {letters [i]}
完成
循环会导致以下错误:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $语法错误操作数预期错误标记是{0..7})
令我困扰的是 $ {#letters [*]}
显然正确地被评估为数字7.但是尽管如此,即使我们刚刚看到与 {0..7}
完美的作品。
这是什么原因?
我运行的是OS X 10.12.2,GNU bash version 3.2 。
在扩展参数之前进行扩展扩展,因此不能将变量作为范围的一部分使用。 / p>
将数组扩展为值列表:
$ {字母[@]};做
echo$ letter
完成
或者,扩大索引把数组放到一个列表中:
$ $ $ $ $ $!!$ {@字母[@]};做
回声$ {letters [i]}
完成
在评论(感谢)中提到,这两种方法也适应稀疏阵列;你不能总是假定一个数组为每个 0
和 $ {#字母[@ ]}
。
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.
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[@]}
.
这篇关于Bash for循环语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!