из man-страницы 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.
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
объединяет все свои аргументы, которые затем запускаются как одна команда. источник
считывает содержимое файла и выполняет его. eval
может строить команды только из своих аргументов, но не stdin
. Так что нельзя делать так:
printf "ls" | eval
Ваш пример дает тот же результат, но цель eval
и source
различна. source
обычно используется для предоставления библиотеки для других скриптов, а eval
используется только для оценки команд. По возможности следует избегать использования eval
, потому что нет гарантии, что выведенная строка чиста; мы должны провести некоторые проверки работоспособности, используя вместо этого подоболочку
.
Когда вы запускаете команды последовательностей внутри фигурных скобок {}
, все команды выполняются в текущем shell вместо подоболочки (что имеет место, если вы выполняете внутри круглых скобок (см. ссылку на bash )).
Использование subshell ()
использует больше ресурсов, но это не влияет на вашу текущую среду. Использование {}
запускает все команды в текущей оболочке, поэтому это влияет на вашу среду. В зависимости от вашей цели вы можете выбрать одну из них.