Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between 'eval $command' and $command?

Tags:

bash

eval

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?

like image 384
NPS Avatar asked Jan 05 '23 07:01

NPS


2 Answers

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.

like image 73
John Zwinck Avatar answered Jan 11 '23 22:01

John Zwinck


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.

like image 31
codeforester Avatar answered Jan 11 '23 20:01

codeforester