Shell 脚本“for"循环语法 [英] Shell script "for" loop syntax
本文介绍了Shell 脚本“for"循环语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经完成了以下工作:
I have gotten the following to work:
for i in {2..10}
do
echo "output: $i"
done
它产生一堆output: 2
、output: 3
,依此类推.
It produces a bunch of lines of output: 2
, output: 3
, so on.
但是,尝试运行以下内容:
However, trying to run the following:
max=10
for i in {2..$max}
do
echo "$i"
done
产生以下内容:
output: {2..10}
如何让编译器意识到它应该将 $max 视为数组的另一端,而不是字符串的一部分?
How can I get the compiler to realize it should treat $max as the other end of the array, and not part of a string?
推荐答案
大括号扩展,{x..y} 在其他扩展之前执行,因此您不能将其用于可变长度序列.
Brace expansion, {x..y} is performed before other expansions, so you cannot use that for variable length sequences.
相反,使用 seq 2 $max
方法作为 用户 mob 声明.
Instead, use the seq 2 $max
method as user mob stated.
因此,对于您的示例,它将是:
So, for your example it would be:
max=10
for i in `seq 2 $max`
do
echo "$i"
done
这篇关于Shell 脚本“for"循环语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文