Between the following alternatives…
-
with
eval
.comd="ls" eval "$comd"
-
with
source /dev/stdin
printf "ls" | source /dev/stdin
-
with
source /dev/stdin
and( )
or{ }
( printf "ls" ) | source /dev/stdin { printf "ls"; } | source /dev/stdin
(When we run
printf
in{ }
, is there any benefit other than not using subshell?)-
What is the difference between them?
-
Which is preferred?
-
Which is the preferred way to run commands?
()
or{}
?
-
Best Answer
from
bash manpage
:There are no differences between the two ways.
There is only one note:
eval
concatenated all of its arguments, which is then run as a single command.source
reads the contents of a file and executes them.eval
can only build commands from its arguments, notstdin
. So you can not do like this:Your example provides the same result, but the purpose of
eval
andsource
is different.source
is usually used for providing a library for other scripts, whileeval
is used only to evaluate commands. You should avoid usingeval
if possible, because there is no guarantee that the evaled string is clean; we must do some sanity checks, usingsubshell
instead.When you run sequences commands inside curly brace
{ }
, all commands are run in the current shell, instead of a subshell (which is the case if you run inside parentheses (see bash reference)).Using
subshell ( )
uses more resources, but your current environment is not affected. Using{ }
runs all the commands in the current shell, so your environment is affected. Depending on your purpose, you can choose one of them.