What's the difference between "eval $ command" and $ command?
Try the following:
y='FOO=hello; echo $FOO'
eval $y
He is typing hello
. But this:
$y
is talking:
- bash: FOO = hello ;: command not found
So when you speak eval $y
, you have accurately entered the text $y
into the interpreter. But when you just say $y
, it should be a command that can be run, not some other tokens that the interpreter needs to parse (in the above example, variable assignment).
If you know the variable contains an executable command, you can run it without eval
. But if a variable can contain Bash code that is not just an executable command (i.e. something that you could imagine going to a C function exec()
), you need eval
.
source to share
To expand on @JohnZwinck's great answer , have a look at these examples as well:
command='ls | wc -l'
eval $command
# outputs the correct result => 17
$command
ls: -l: No such file or directory
ls: wc: No such file or directory
ls: |: No such file or directory
command='ls -l $PWD'
eval $command
# outputs the contents of current directory
$command
# runs 'ls -l $PWD' literally as a command and ls tries to lookup $PWD as a file
ls: $PWD: No such file or directory
So eval
builtin interprets its arguments in the same way as shell does. However, in the case, the $command
shell expands the variable and literally treats the content as a command.
source to share