bash 使用大括号扩展范围内的变量馈送到 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9911056/
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
Using a variable in brace expansion range fed to a for loop
提问by spraff
Here is myscript.sh
这是 myscript.sh
#!/bin/bash
for i in {1..};
do
echo $i;
done
If I run myscript.sh 3
the output is
如果我运行myscript.sh 3
输出是
3 {1..3}
instead of
代替
3 1
3 2
3 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?
显然$3
包含正确的值,那么为什么不像for i in {1..$1}
我for i in {1..3}
直接写的那样表现呢?
回答by jordanm
You should use a C-style for loop to accomplish this:
您应该使用 C 样式的 for 循环来完成此操作:
for ((i=1; i<=; i++)); do
echo $i
done
This avoids external commands and nasty eval statements.
这避免了外部命令和讨厌的 eval 语句。
回答by Oliver Charlesworth
Because brace expansion occurs before expansion of variables. http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion.
因为大括号扩展发生在变量扩展之前。http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion。
If you want to use braces, you could so something grim like this:
如果你想使用大括号,你可以像这样严峻:
for i in `eval echo {1..}`;
do
echo $i;
done
Summary: Bash is vile.
总结:Bash 是邪恶的。
回答by kev
You can use seq
command:
您可以使用seq
命令:
for i in `seq 1 `
Or you can use the C-style for...loop
:
或者您可以使用 C 风格for...loop
:
for((i=1;i<=;i++))
回答by Jonathan Cross
Here is a way to expand variables inside braces without eval:
这是一种无需 eval 即可在大括号内扩展变量的方法:
end=3
declare -a 'range=({'"1..$end"'})'
We now have a nice array of numbers:
我们现在有一个很好的数字数组:
for i in ${range[@]};do echo $i;done
1
2
3
回答by Joshua
I know you've mentioned bash in the heading, but I would add that 'for i in {$1..$2}' works as intended in zsh. If your system has zsh installed, you can just change your shebang to zsh.
我知道你在标题中提到了 bash,但我想补充一点,'for i in {$1..$2}' 在 zsh 中按预期工作。如果您的系统安装了 zsh,您只需将您的 shebang 更改为 zsh。
Using zsh with the example 'for i in {$1..$2}' also has the added benefit that $1 can be less than $2 and it still works, something that would require quite a bit of messing about if you wanted that kind of flexibility with a C-style for loop.
将 zsh 与示例 'for i in {$1..$2}' 一起使用还具有额外的好处,即 $1 可以小于 $2 并且它仍然有效,如果您想要这种灵活性,则需要相当多的麻烦带有 C 风格的 for 循环。