此脚本中的最后一行无法按我预期的方式运行:
myfile="afile.txt"
mycmd='cat $myfile'
eval $mycmd
echo eval $mycmd
此处 echo eval $mycmd
打印 eval cat $myfile
。
如何打印 eval cat afile.txt
?
最佳答案
让我们一步步来:
当你这样做时:
mycmd='cat $myfile'
您阻止 shell 插入 $myfile
。因此:
$ echo $mycmd
cat $myfile
如果要允许插值,可以使用双引号:
$ mycmd="echo $myfile" #Double quotes!
$ echo "$mycmd"
cat afile.txt
当然,当您执行 eval
时,这会卡住 $mycmd
的解释。
$ 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
比较一下:
$ 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
:
$ echo $(eval "echo $mycmd")
$ cat afile.txt
$ myfile=bfile.txt
$ echo $(eval "echo $mycmd")
cat bfile.txt
关于bash - 在 bash 中评估字符串中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18219262/