What's the difference between:
eval echo lala
and:
command="echo lala"
$command
They both seem to have the same effect but I might be missing something. Also, if they do have the same effect, what's the point of eval command?
Try this:
y='FOO=hello; echo $FOO'
eval $y
It prints hello.
But this:
$y
says:
-bash: FOO=hello;: command not found
So when you say eval $y it is just as if you had typed the content of $y into the interpreter. But when you just say $y it needs to be a command that can be run, rather than some other tokens that the interpreter needs to parse (in the above example, a variable assignment).
If you know that a variable contains an executable command you can run it without eval. But if the variable might contain Bash code which is not simply an executable command (i.e. something you could imagine passing to the C function exec()), you need eval.
To expand on @JohnZwinck's great answer, 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 would do. However, in case of $command, shell expands the variable and literally treats the content as a command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With