使用{$ var}在for循环中进行变量替换 [英] Variable substitution in a for-loop using {$var}
本文介绍了使用{$ var}在for循环中进行变量替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对bash脚本非常陌生,我正在尝试通过制作一个只要求输入数字范围的小脚本来进行练习.我会输入ex.5..20,它应该显示范围,但是-无论输入什么,它都将回显(在本示例中为"5..20"),并且不扩展变量.有人可以告诉我我在做什么错吗?
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?
脚本:
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
推荐答案
- bash中的括号扩展不会扩展参数(与zsh不同)
- 您可以通过使用
eval
和命令替换$()
来解决此问题. -
eval
是邪恶的,因为您需要清理输入内容,否则人们可以输入rm -rf/;
和eval
这样的范围 - 请勿使用
function
关键字,它不是POSIX,已被弃用 - 使用
read
的-p
标志代替echo
- Brace expansion in bash does not expand parameters (unlike zsh)
- You can get around this through the use of
eval
and command substitution$()
eval
is evil because you need to sanitize your input otherwise people can enter ranges likerm -rf /;
andeval
will run that- Don't use the
function
keyword, it is not POSIX and has been deprecated - use
read
's-p
flag instead of 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
注意:在这种情况下,使用 eval
是可以的,因为您只是 echo
在范围内
Note: In this case the use of eval
is OK because you are only echo
'ing the range
这篇关于使用{$ var}在for循环中进行变量替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文