bash - 在 bash 中评估字符串中的变量

标签 bash

此脚本中的最后一行无法按我预期的方式运行:

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/

相关文章:

bash - 在 shell 脚本 bash 中获取结束时间

bash - 在一个文件中查找不在另一个文件中的行的快速方法?

正则表达式匹配行尾

linux - 奇怪的 "sh"行为

node.js - bash:npm:在 Debian 9 中找不到命令

bash - 为什么从 cli 运行 aws update-service 会导致类似 vim 的窗口弹出,需要一些输入?

Ruby 版本在终端和 bash 中有所不同

linux - 将命令作为变量传递给另一个程序?

bash - 使用ssh将变量发送到远程服务器

arrays - Bash 数组操作