Using the eval command in Linux to run variables as commands

eval命令允许您将变量的内容作为命令运行,并且非常有用,尤其是在脚本中。

  • 在脸书上分享
  • 分享到Twitter
  • 分享LinkedIn
  • Share on Reddit
  • 通过电子邮件分享
  • 打印资源
可变键键盘
迈克·劳伦斯(CC BY 2.0)

可能有很多Linux用户从未遇到过评估command. In fact, it’s not really a "command", but内置的狂欢这是为了处理变量的值作为命令。例如,如果您设置了一个包含命令以显示当前时间在澳大利亚悉尼的变量,则可能看起来像这样:

$ dt =“ tz ='澳大利亚/悉尼的日期”

然后,您可以这样运行:

$ eval $dt

星期四706:32:14 AM AEST 2022

这样做可以为您节省记忆的麻烦日期命令语法并指定一个时区,但让我们更仔细地看一下评估看看它还可以为您做什么。

Bash Man页面会告诉您一些有关评估命令,尽管您必须向下滚动近5,000行才能找到它。毕竟,没有人页面的内置页面。这就是它告诉您的:

这args are read and concatenated together into a single com-

命令。然后由外壳读取和执行此命令,并执行

它的退出状态将作为评估的价值返回。如果有

没有ARGS,或仅零论点,eval返回0。

当然,对于您通过在终端窗口中键入命令所做的任何事情,评估不太可能为您节省很多时间或精力。毕竟,您可以创建一个别名为您做同样的工作。这是这样的外观:

$别名DT =“ TZ ='澳大利亚/悉尼'日期”

$ dt

星期四706:37:31 AM AEST 2022

将该别名保存在.bashrc文件中,并且您可以轻松地检查悉尼的时间是什么时候。

但是,当您将复杂的命令构成零件时(尤其是在运行时需要收集必要数据的脚本中)评估运行命令可以使运行命令变得更加容易。

例如,在进行工作时最近的脚本,,,,I needed to find words that were five letters long, had specific letters in known positions and other specific letters in uncertain positions. I also knew that a number of letters were not included in the words that I needed to find. Step-by-step, the script built a long string ofgrepcommands to look through the words file to find only the words that fit my specifications. Here’s an example of what such a command might look like with all of itsgrep(匹配)及其grep -v(忽略)命令及其发现的比赛:

$ grep ^ch..t $/usr/share/dict/单词|eval grep -v'q'|grep -v'W'|grep -v'r'|grep -v'y'|grep -v'u'|grep -v'i'|grep -v'o'|grep -v'p'|grep -v's'| grep -v 'd' | grep -v 'f' | grep -v 'g' | grep -v 'j' | grep -v 'k' | grep -v 'l' | grep -v 'z' | grep -v 'x' | grep -v 'v' | grep -v 'b' | grep -v 'n' | grep -v 'm' | grep a | grep e | grep -v ..a.. | grep -v ...e.

欺骗

实际上,如果您使用单词文件运行该命令,则应得到相同的响应。如果将其变成如下所示的变量,则将其工作相同。

$ cmd="grep ^ch..t$ /usr/share/dict/words | grep -v 'q' | grep -v 'w' | grep -v 'r' | grep -v 'y' | grep -v 'u' | grep -v 'i' | grep -v 'o' | grep -v 'p' | grep -v 's' | grep -v 'd' | grep -v 'f' | grep -v 'g' | grep -v 'j' | grep -v 'k' | grep -v 'l' | grep -v 'z' | grep -v 'x' | grep -v 'v' | grep -v 'b' | grep -v 'n' | grep -v 'm' | grep a | grep e | grep -v ..a.. | grep -v ...e."

$ eval $cmd

欺骗

My script uses评估to run the$ cmdvariable as a command and passes the output to the柱子当有数十个或数百个匹配单词时,命令使输出更有用。显示的示例中的结果是单词文件中的近半百万行中摘下的单词“作弊”。我需要做的就是回答有关我所知道和不知道的几个问题。

评估$ CMD |柱子

包起来

评估命令可用于运行作为变量保存的简单或非常复杂的命令。它在变量中评估命令和参数,然后执行它们。当您构建长而复杂的命令时,这是最有用的 - 尤其是在脚本中,详细信息取决于在运行脚本时更改或响应的数据时。

联合国。

有关的:

版权© 2022 IDG Communications, Inc.

企业网络中的10家最强大的公司2022