使用变量作为循环终止条件的Bash循环

25

我经常使用众所周知的语法在Bash中编写for循环:

for i in {1..10}  [...]

现在,我正尝试编写一个其中顶部由变量定义的代码:

TOP=10
for i in {1..$TOP} [...]

我尝试了各种圆括号、花括号、求值等方式,通常会返回一个"bad substitution"错误。

如何编写 for 循环,使得上限取决于变量而不是硬编码的值?


可能是重复的问题:如何在Bash中迭代一系列数字? - l0b0
3个回答

41

您可以使用如下for循环来迭代变量$TOP

for ((i=1; i<=$TOP; i++))
do
   echo $i
   # rest of your code
done

9

如果你有GNU系统,你可以使用seq生成各种序列,包括这个。

for i in $(seq $TOP); do
    ...
done

不建议使用seq来进行大括号扩展。在BSD/GNU之间的行为并不完全相同。 - Daenyth
@daenyth很好注意到当大括号扩展是一种可行的替代方案时,但这个问题的重点是大括号扩展无法与变量边界一起使用。 - Kevin

2

答案部分在 这里 :请查看示例11-12.C风格for循环

这里是一个总结,但请注意你的bash解释器(/bin/bash --version)会影响你问题的最终答案:

# Standard syntax.
for a in 1 2 3 4 5 6 7 8 9 10

# Using "seq" ...
for a in `seq 10`

# Using brace expansion ...
# Bash, version 3+.
for a in {1..10}

# Using C-like syntax.
LIMIT=10
for ((a=1; a <= LIMIT ; a++))  # Double parentheses, and "LIMIT" with no "$".

# another example
lines=$(cat $file_name | wc -l)
for i in `seq 1 "$lines"`

# An another more advanced example: looping up to the last element count of an array :
for element in $(seq 1 ${#my_array[@]})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接