我经常使用众所周知的语法在Bash中编写for循环:
for i in {1..10} [...]
现在,我正尝试编写一个其中顶部由变量定义的代码:
TOP=10
for i in {1..$TOP} [...]
我尝试了各种圆括号、花括号、求值等方式,通常会返回一个"bad substitution"错误。
如何编写 for 循环,使得上限取决于变量而不是硬编码的值?
您可以使用如下for循环来迭代变量$TOP
:
for ((i=1; i<=$TOP; i++))
do
echo $i
# rest of your code
done
如果你有GNU系统,你可以使用seq
生成各种序列,包括这个。
for i in $(seq $TOP); do
...
done
seq
来进行大括号扩展。在BSD/GNU之间的行为并不完全相同。 - Daenyth答案部分在 这里 :请查看示例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[@]})