繁体   English   中英

用可变的高端编写bash for循环

[英]Writing a bash for-loop with a variable top-end

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

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

现在,我正在尝试编写一个由变量定义顶部的示例:

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

我尝试过各种括号,大括号,求值法等,通常会返回错误“替换错误”。

如何编写我的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

答案部分存在 :请参见示例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[@]})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM