Search code examples
basheval

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


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?


Solution

  • 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.