在bash for循环中评估表达式 [英] Evaluate expression inside bash for loop
问题描述
如果执行此操作,将得到预期的结果.
If I do this, I get the result as expected.
for i in {125..129}; do echo $i; done
125
126
127
128
129
但是,当我这样做时?我有点奇怪.
But when I do this? I get something weired.
for i in {$((1+(25-1)*500))..$((25*500))}; do echo $i; done
{12001..12500}
我希望在循环变量中传递一个变量,例如 $((1 +($ j-1)* 500))
I wish to pass a variable inside the loop variables like $((1+($j-1)*500))
推荐答案
Bash的括号扩展有局限性.您想要的是 seq
:
Bash's brace expansion has limitations. What you want is seq
:
for i in $( seq $((1+(25-1)*500)) $((25*500)) ); do echo $i; done
以上内容将循环显示从12001年到12500年的所有数字.
The above will loop over all numbers from 12001 to 12500.
seq
类似于bash的花括号:
seq
is similar to bash's braces:
$ echo {2..4}
2 3 4
$ echo $(seq 2 4)
2 3 4
seq
的主要优点是它的参数不仅可以包括如上所示的算术表达式,还可以包括shell变量:
The key advantage of seq
is that its arguments can include not just arithmetic expressions, as shown above, but also shell variables:
$ x=4; echo $(seq $((x-2)) $x)
2 3 4
通过对比,大括号符号将不接受.
By contrast, the brace notation will accept neither.
seq
是GNU实用程序,可在所有linux系统以及OSX的最新版本中使用.较旧的BSD系统可以使用名为 jot
的类似实用程序.
seq
is a GNU utility and is available on all linux systems as well as recent versions of OSX. Older BSD systems can use a similar utility called jot
.
这篇关于在bash for循环中评估表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!