bash 使用 {$var} 的 for 循环中的变量替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5447302/
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
Variable substitution in a for-loop using {$var}
提问by ZDRuX
I'm very new to bash scripting and I'm trying to practice by making this little script that simply asks for a range of numbers. I would enter ex. 5..20 and it should print the range, however - it just echo's back whatever I enter ("5..20" in this example) and does not expand the variable. Can someone tell me what I'm doing wrong?
我对 bash 脚本很陌生,我正在尝试通过制作这个只要求输入一系列数字的小脚本来练习。我会输入前。5..20 并且它应该打印范围,但是 - 它只是回显我输入的任何内容(在本例中为“5..20”)并且不会扩展变量。有人可以告诉我我做错了什么吗?
Script:
脚本:
echo -n "Enter range of number to display using 0..10 format: "
read range
function func_printrage
{
for n in {$range}; do
echo $n
done
}
func_printrange
回答by SiegeX
- Brace expansion in bash does not expand parameters (unlike zsh)
- You can get around this through the use of
evaland command substitution$() evalis evil because you need to sanitize your input otherwise people can enter ranges likerm -rf /;andevalwill run that- Don't use the
functionkeyword, it is not POSIX and has been deprecated - use
read's-pflag instead of echo
- bash 中的大括号扩展不扩展参数(与 zsh 不同)
- 您可以通过使用
eval和命令替换来解决这个问题$() eval是邪恶的,因为你需要清理,否则您输入的人可以进入喜欢的范围rm -rf /;和eval将运行- 不要使用
function关键字,它不是 POSIX 并且已被弃用 - 使用
read's-p标志而不是 echo
However, for learning purposes, this is how you would do it:
但是,出于学习目的,您可以这样做:
read -p "Enter range of number to display using 0..10 format: " range
func_printrange()
{
for n in $(eval echo {$range}); do
echo $n
done
}
func_printrange
Note:In this case the use of evalis OK because you are only echo'ing the range
注意:在这种情况下,使用eval是可以的,因为您只是echo在范围内
回答by kurumi
One way is to use eval,
crude example,
一种方法是使用eval,粗略的例子,
for i in $(eval echo {0..$range}); do echo $i; done
the other way is to use bash's C style forloop
另一种方法是使用 bash 的 C 风格for循环
for((i=1;i<=20;i++))
do
...
done
And the last one is more faster than first (for example if you have $range > 1 000 000)
最后一个比第一个更快(例如,如果你有 $range > 1 000 000)
回答by Morgen
One way to get around the lack of expansion, and skip the issues with eval is to use command substitution and seq.
解决缺乏扩展并跳过 eval 问题的一种方法是使用命令替换和 seq。
Reworked function (also avoids globals):
重新设计的功能(也避免了全局变量):
function func_print_range
{
for n in $(seq ); do
echo $n
done
}
func_print_range $start $end
回答by Rafe Kettler
Use ${}for variable expansion. In your case, it would be ${range}. You left off the $ in ${}, which is used for variable expansion and substitution.
使用${}的变量扩展。在您的情况下,它将是 ${range}。您省略了 ${} 中的 $,它用于变量扩展和替换。

