评估字符串中的变量 [英] Evaluating variables in a string
本文介绍了评估字符串中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此脚本中的最后一行将无法正常运行:
The last line in this script won't work as I expect:
myfile="afile.txt"
mycmd='cat $myfile'
eval $mycmd
echo eval $mycmd
此处echo显示'eval cat $ myfile'.如何打印"eval cat afile.txt"?
Here echo prints 'eval cat $myfile'. How can I print 'eval cat afile.txt'?
推荐答案
让我们一步一步来做吧:
Let's take things step by step:
执行此操作时:
mycmd='cat $myfile'
可以防止外壳插值$myfile
.因此:
You prevent the shell from interpolating $myfile
. Thus:
$ echo $mycmd
cat $myfile
如果要允许插值,可以使用双引号:
If you want to allow the interpolation, you can use double quotes:
$ mycmd="echo $myfile" #Double quotes!
$ echo "$mycmd"
cat afile.txt
当然,当您执行eval
时,这会冻结解释$mycmd
.
This, of course, freezes the interpretation of $mycmd
when you do an eval
.
$ myfile="afile.txt"
$ mycmd="echo $myfile"
$ echo $mycmd
cat afile.txt
$ eval $mycmd #Prints out afile.txt
$ myfile=bfile.txt
$ eval $mycmd #Still prints out afile.txt and not bfile.txt
将此与以下内容进行比较:
Compare this to:
$ myfile="afile.txt"
$ mycmd='cat $myfile' #Single quotes hide $myfile from the shell
echo $mycmd
cat $myfile #Shell didn't change "$myfile", so it prints as a literal
$ eval $mycmd #Prints out afile.txt
$ myfile=bfile.txt
$ eval $mycmd #Now prints out bfile.txt
您可能想要做的是在回显语句时在回显语句中评估$mycmd
:
What you probably want to do is to evaluate the $mycmd
in an echo statement when you echo it:
$ echo $(eval "echo $mycmd")
$ cat afile.txt
$ myfile=bfile.txt
$ echo $(eval "echo $mycmd")
cat bfile.txt
这篇关于评估字符串中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文