在括号扩展范围内使用变量,将其馈送到for循环 [英] Using a variable in brace expansion range fed to a for loop
本文介绍了在括号扩展范围内使用变量,将其馈送到for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是myscript.sh
Here is myscript.sh
#!/bin/bash
for i in {1..$1};
do
echo $1 $i;
done
如果我运行myscript.sh 3
,则输出为
3 {1..3}
代替
3 1
3 2
3 3
显然$3
包含正确的值,所以for i in {1..$1}
的行为为何与我直接编写for i in {1..3}
的行为不同?
Clearly $3
contains the right value, so why doesn't for i in {1..$1}
behave the same as if I had written for i in {1..3}
directly?
推荐答案
您应该使用C样式的for循环来完成此操作:
You should use a C-style for loop to accomplish this:
for ((i=1; i<=$1; i++)); do
echo $i
done
这避免了外部命令和讨厌的eval语句.
This avoids external commands and nasty eval statements.
这篇关于在括号扩展范围内使用变量,将其馈送到for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文