来自bash manpage
:
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.
source filename [arguments]
Read and execute commands from filename in the current shell
environment and return the exit status of the last command exe‐
cuted from filename. If filename does not contain a slash, file
names in PATH are used to find the directory containing file‐
name. The file searched for in PATH need not be executable.
When bash is not in posix mode, the current directory is
searched if no file is found in PATH. If the sourcepath option
to the shopt builtin command is turned off, the PATH is not
searched. If any arguments are supplied, they become the posi‐
tional parameters when filename is executed. Otherwise the
positional parameters are unchanged. The return status is the
status of the last command exited within the script (0 if no
commands are executed), and false if filename is not found or
cannot be read.
两种方式之间没有区别。
只有一个注释:eval
将其所有参数串联在一起,然后将其作为单个命令运行。source
读取文件的内容并执行它们。eval
只能根据其参数构建命令,而不能根据其参数构建命令stdin
。所以你不能这样:
printf "ls" | eval
你举的例子提供了相同的结果,但目的eval
和source
是不同的。source
通常用于为其他脚本提供库,而eval
仅用于评估命令。eval
如果可能的话,应避免使用,因为不能保证逃逸的字符串是干净的。我们必须做一些检查,subshell
改为使用。
在花括号内运行sequence命令时{ }
,所有命令均在当前shell中运行,而不是在子shell中运行(如果在括号内运行,则是这种情况(请参见bash 参考))。
使用会subshell ( )
占用更多资源,但是您的当前环境不会受到影响。使用using { }
在当前shell中运行所有命令,因此您的环境受到影响。根据您的目的,您可以选择其中之一。