bash for循环问题

bash for loop question

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
How do I iterate over a range of numbers in bash?

当我这样做:

1
2
RANGE_COUNT=28
for i in {0..$RANGE_COUNT} ; do     echo $i; done

我明白了

1
{0..28}

当我这样做:

1
for i in {0..5} ; do     echo $i; done

我明白了:

1
2
3
4
5
6
0
1
2
3
4
5

这是怎么回事?如何让它做我明确想要的事情,显然没有正确说明?


你可以使用c风格循环

1
2
3
4
for((i=1;i<=$RANGE_COUNT;i++))
do
  ...
done

或使用eval

1
for i in $(eval echo {0..$RANGE_COUNT}); do echo $i; done

其他方法包括while循环

1
2
i=0
while ["$i" -le"$RANGE_COUNT" ]; do echo $i; ((i++)); done

来自man bash:

Brace expansion is performed before
any other expansions, and any
characters special to other
expansions are preserved in the
result. It is strictly textual. Bash
does not apply any syntactic
interpretation to the context of
the expansion or the text between the
braces.

因此,在参数扩展之前,它是一种纯粹的文本宏扩展。

Shell是宏处理器和更正式的编程语言之间高度优化的混合。 为了优化典型的使用案例,我们做出了各种妥协; 有时语言会变得更加复杂,有时候会受到限制。


使用算术符号:

1
for ((i=0; i<$RANGE_COUNT; i++)); do echo $i; done