Linux 编写一个带有可变顶端的 bash for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9778741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a bash for-loop with a variable top-end
提问by abelenky
I frequently write for-loops in bash with the well-known syntax:
我经常使用众所周知的语法在 bash 中编写 for 循环:
for i in {1..10} [...]
Now, I'm trying to write one where the top is defined by a variable:
现在,我正在尝试编写一个由变量定义的顶部:
TOP=10
for i in {1..$TOP} [...]
I've tried a variety of parens, curly-brackets, evaluations, etc, and typically get back an error "bad substitution".
我尝试了各种括号、花括号、评估等,通常会得到一个错误“坏替换”。
How can I write my for-loop so that the limit depends on a variable instead of a hard-coded value?
如何编写我的 for 循环,以便限制取决于变量而不是硬编码值?
采纳答案by anubhava
You can use for loop like this to iterate with a variable $TOP
:
您可以像这样使用 for 循环来迭代变量$TOP
:
for ((i=1; i<=$TOP; i++))
do
echo $i
# rest of your code
done
回答by Kevin
If you have a gnu system, you can use seq
to generate various sequences, including this.
如果你有一个 gnu 系统,你可以用它seq
来生成各种序列,包括这个。
for i in $(seq $TOP); do
...
done
回答by hornetbzz
Answer is partly there: see Example 11-12. A C-style for loop.
答案部分在那里:参见例 11-12。一个 C 风格的 for 循环。
Here is a summary from there, but be aware the final answer to your question depends on your bash interpreter (/bin/bash --version):
这是那里的摘要,但请注意,您问题的最终答案取决于您的 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[@]})