eval
是一个bash内部命令,在bash
手册页中进行了描述。
eval [arg ...]
The args are read and concatenated together into a single com-
mand. This command is then read and executed by the shell, and
its exit status is returned as the value of eval. If there are
no args, or only null arguments, eval returns 0.
通常它与命令替换组合使用。比如向用一个字符串当做命令来执行,而命令替换会报错,此时就可以用它来将字符串连接为一个命令来执行。
-
[bob@centos home]$ ( echo VAR=value ) bash: VAR=value: command not found [bob@centos home]$echo $VAR <empty line>
shell尝试执行
echo
和VAR=value
作为两个单独的命令。它会引发关于第二个字符串的错误。任务仍然无效。 -
shell会合并(串联)两个字符串,[bob@centos home]$ eval $( echo VAR=value ) [bob@centos home]$ echo $VAR value
echo
和
VAR=value
根据适当的规则解析此单个单元并执行它。
eval
可以是非常危险的命令。eval
必须仔细检查命令的任何输入,以避免出现安全问题。
参考:
1、shell - What is the "eval" command in bash? - Unix & Linux Stack Exchange
2、POSIX 1003.1 - man page for eval (posix section 1posix) - Unix & Linux Commands