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

What's the difference between:

eval echo lala



command="echo lala"


They both seem to have the same effect, but I might be missing something. Also, if they do have the same effect, what does the command mean eval



source to share

2 answers

Try the following:

y='FOO=hello; echo $FOO'
eval $y


He is typing hello

. But this:



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




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



All Articles