Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

What can you do with the eval command? Why is it useful? Is it some kind of a built-in function in bash? There is no man page for it..

share|improve this question
14  
Use type command to learn of what type a command is. (type eval in ths case) – rozcietrzewiacz Oct 22 '11 at 20:38
    
"eval is a shell builtin" – Nuno Rafael Figueiredo Jul 11 at 16:26
up vote 54 down vote accepted

eval is part of POSIX. Its an interface which can be a shell built-in.

Its described in the "POSIX Programmer's Manual": http://www.unix.com/man-page/posix/1posix/eval/

eval - construct command by concatenating arguments

It will take an argument and construct a command of it, which will be executed by the shell. This is the example of the manpage:

1) foo=10 x=foo
2) y='$'$x
3) echo $y
4) $foo
5) eval y='$'$x
6) echo $y
7) 10
  1. In the first line you define $foo with the value '10' and $x with the value 'foo'.
  2. Now define $y, which consists of the string '$foo'. The dollar sign must be escaped with '$'.
  3. To check the result, echo $y.
  4. The result will be the string '$foo'
  5. Now we repeat the assignment with eval. It will first evaluate $x to the string 'foo'. Now we have the statement y=$foo which will get evaluated to y=10.
  6. The result of echo $y is now the value '10'.

This is a common function in many languages, e.g. Perl and JavaScript. Have a look at perldoc eval for more examples: http://perldoc.perl.org/functions/eval.html

share|improve this answer
3  
In shell terminology, eval is a built-in, not a function. In practice, built-ins behave a lot like functions that don't have an in-language definition, but not quite (as becomes apparent if you are twisted enough to define a function called eval). – Gilles Oct 23 '11 at 1:17
    
thx, fixed that :-) – echox Oct 25 '11 at 14:14
2  
What is the difference between eval and backticks ` ? – JohnyTex Mar 20 '15 at 9:16
    
Backticks are shorthand for executing another entire shell, meaning you'll have another child bash/sh process running within your script. – Aaron R. Oct 19 '15 at 15:38

Yes, eval is a bash internal command so it is described in bash man page.

eval [arg ...]
    The  args  are read and concatenated together into a single com-
    mand.  This command is then read and executed by the shell,  and
    its  exit status is returned as the value of eval.  If there are
    no args, or only null arguments, eval returns 0.

Usually it is used in combination with a Command Substitution. Without an explicit eval, the shell tries to execute the result of a command substitution, not to evaluate it.

Note the difference:

  1. The shell tries to execute VAR=value as a command:

    andcoz@...:~> $( echo VAR=value )
    bash: VAR=value: command not found
    
  2. The shell evaluates the command:

    andcoz@...:~> eval $( echo VAR=value )
    andcoz@...:~> echo $VAR
    value
    

Last but not least, eval can be a very dangerous command. Any input to an eval command must be carefully checked to avoid security problems.

share|improve this answer

eval has no man page because it is not a separate external command, but rather a shell built-in, meaning a command internal to and known only by the shell (bash). The relevant part of the bash man page says:

eval [arg ...]
    The args are read and concatenated together into a single command.  
    This command is then  read  and executed by the shell, and its exit 
    status is returned as the value of eval.  If there are no args, or only 
    null arguments, eval returns 0

In addition, the output if help eval is:

eval: eval [arg ...]
    Execute arguments as a shell command.

    Combine ARGs into a single string, use the result as input to the shell,
    and execute the resulting commands.

    Exit Status:
    Returns exit status of command or success if command is null.

eval is a powerful command and if you intend to use it you should be very careful to head off the possible security risks that come with it.

share|improve this answer
2  
+1 for including the link to the Wooledge FAQ – jasonwryan Oct 22 '11 at 22:12

The eval statement tells the shell to take eval’s arguments as command and run them through the command-line. It is useful in a situation like below:

In your script if you are defining a command into a variable and later on you want to use that command then you should use eval:

/home/user1 > a="ls | more"
/home/user1 > $a
bash: command not found: ls | more
/home/user1 > # Above command didn't work as ls tried to list file with name pipe (|) and more. But these files are not there
/home/user1 > eval $a
file.txt
mailids
remote_cmd.sh
sample.txt
tmp
/home/user1 >
share|improve this answer
    
The comment in line 4 of your example is wrong: It should be "Above command didn't work because bash tried to find a command called ls | more. In other words: The single command name consisted of nine characters, including the spaces and the pipe symbol. – cfi Oct 16 '15 at 13:41

eval is a feature of most interpreted languages (TCL, python, ruby...), not only shells. It's used to evaluate code dynamically.

In shells, it's implemented as a shell builtin command.

Basically, eval takes a string as argument and evaluates/interprets the code in it. In shells, eval can take more than one argument, but eval just concatenates those to form the string to evaluate.

It's very powerful because you can construct code dynamically and run it, something you can't do in compiled languages like C.

Like:

varname=$1 varvalue=$2
eval "$varname=\$varvalue" # evaluate a string like "foo=$varvalue"
                           # which in Bourne-like shell language
                           # is a variable assignment.

But it's also dangerous as it's important to sanitize the dynamic (externally provided) parts of what is passed to eval for the very reason it's interpreted as shell code.

For instance, above if $1 is evil-command; var, eval would end-up evaluating the evil-command; var=$varvalue shell code and then run that evil-command.

The evilness of eval is often over-exaggerated.

OK, it's dangerous, but at least we know it's dangerous.

A lot of other commands will evaluate shell code in its arguments if not sanitized, like (depending on the shell), [ aka test, export, printf, GNU sed, awk, and of course sh/bash/perl and all interpreters...

Examples (here using uname as the evil-command and $a as externally provided unsanitized data):

$ a='$(uname>&2)' sh -c 'eval "echo $a"'
Linux

$ a='x[0$(uname>&2)]' mksh -c 'export "$a=$b"'
Linux
$ a='x[0$(uname>&2)]' ksh93 -c 'printf "%d\n" "$a"'
Linux
0
$ a='x[0$(uname>&2)]' ksh93 -c '[ "$a" -gt 0 ]'
Linux
$ a=$'bar/g;e uname>&2\n;s//'; echo foo | sed "s/foo/$a/g"
Linux
bar
$ a='";system("uname");"'; awk "BEGIN{print \"$a\"}"

Linux
$ a=';uname'; sh -c "echo $a"

Linux

Those sed, export... commands could be considered more dangerous because while it's obvious eval "$var" will cause the content of $var as shell code, it's not so obvious with sed "s/foo/$var/" or export "$var=value" or [ "$var" -gt 0 ]. The dangerosity is the same, but it's concealed in those other commands.

share|improve this answer
    
@BinaryZebra, sed like eval is being passed a string contained in a variable, and for both, the content of that string ends up being evaluated as shell code, so sed is as dangerous as eval, that's what I'm saying. sed is being passed a string containing uname (uname has not been executed so far) and through the invocation of sed, the uname command ends up being executed. Like for eval. In sed 's/foo/$a/g', you're not passing unsanitized data to sed, that's not what we're talking about here. – Stéphane Chazelas Dec 19 '15 at 20:52

What is eval?

eval is a shell command which is usually implemented as a builtin.

In POSIX it is listed as part of "2.14. Special Built-In Utilities" at the entry "eval".
What builtin means is:

The term "built-in" implies that the shell can execute the utility directly and does not need to search for it.

What does it do?

In simple terms: makes an input line to be parsed twice.

How does it do that?

The shell has a sequence of steps that it follows to "process" a line. You could look at this image and realize that eval is the only line that goes up, back to step 1, on the left. From the POSIX description:

2.1 Shell Introduction

  1. The shell reads its input ....
  2. The shell breaks the input into tokens: words and operators
  3. The shell parses the input into simple and compound commands.
  4. The shell performs various expansions (separately) ...
  5. The shell performs redirection and removes redirection operators and their operands from the parameter list.
  6. The shell executes a function, built-in, executable file, or script ...
  7. The shell optionally waits for the command to complete and collects the exit status.

At step 6 a built-in will be executed.
At step 6 eval causes the processed line to be sent back to step 1.
It is the only condition under which the execution sequence goes back.

That is why I say: With eval an input line is parsed twice.

Effects of parsing twice.

The first.

And most important effect to understand. Is that one consequence of the first time a line is subject to the seven shell steps shown above, is quoting. Inside step 4 (expansions), there is also a sequence of steps to perform all expansions, the last of which is Quote Removal:

Quote removal shall always be performed last.

So, always, there is one level of quoting removed.

Second.

As consequence of that first effect, additional/different parts of the line become exposed to the shell parsing and all the other steps.

Example.

Indirection.

That allows to execute indirect expansions:

a=b b=c    ;    eval echo \$$a            ### shall produce "c"

Why? Because on the first loop, the first $ is quoted.
As such, it is ignored for expansions by the shell.
The next $ with the name a is expanded to produce "b".
Then, one level of quoting is removed, making the first $ unquoted.
End of first loop.

It is then, on the second loop that the string $b is read by the shell.
Then expanded to "c"
And given as an argument to echo.

To "see" what eval will produce on the first loop (to be evaluated again), use echo. Or any command/script/program that clearly shows the arguments:

$ a=b b=c
$ eval echo \$$a;
c

Replace eval by echo to "see" what is happening:

$ echo echo \$$a
echo $b

It is also possible to show all the "parts" of a line with:

$ printf '<%s> ' echo \$$a
<echo> <$b>

Which, in this example, is only one echo and one variable, but remember it to help in evaluating more complex cases.

A correction.

It must be said that: there is a mistake in the code above, can you see it?.
Easy: there are some quotes missing.

How? you may ask. Simple, let's change the variables (not the code):

$ a=b b="hi     jk"
$ eval echo \$$a
hi jk

See the missing spaces?
That is because the value inside $b was split by the shell.

If that does not convince you, try this:

$ a=b b="hi  *  jk"
$ eval echo \$$a              ### warning this will expand to the list  
                              ### of all files in the present directory.

Why?

Missing quotes. To make it work correctly (add internal "$a"and external \" quotes).
Try this (is perfectly safe):

$ a=b b="hi      *       jk"
$ eval echo \" \$"$a" \"
hi      *       jk

About the manual:

There is no man page for it..

No, there is not an independent man page for this. The search for manual with man -f eval or even apropos eval show no entry.

It is included inside man bash. As is any built-in.
Search for "SHELL BUILTIN COMMANDS" and then for "eval".

An easier way to get help is: In bash, you could do help eval to see the help for the built-in.

Why is eval called evil?

Because it is binding text to code dynamically.

In other words: it converts the list of its arguments (and/or expansions of such arguments) into an executed line. If for any reason, an argument has been set by an attacker, you will be executing attacker code.

Or even simpler, with eval you are telling whoever defined the value of one or several arguments:

C'mon, sit here and type any command line, I will execute it with my powers.

Is that dangerous? Should be clear for everyone that it is.

The safety rule for eval should be:
Only execute eval on variables to which you have given it's value.

Read more detail here.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.