# Bash - Eval



## fullauto (Apr 20, 2013)

Can someone please explain to me in simple terms where, and why one would use eval? I have read quite a bit on it, but it eludes me.

Thank you in advance.


----------



## expl (Apr 21, 2013)

eval() is a common name for an operation of execution of native syntax from a form of a string in interpreted languages like Python, JavaScript and others (name can differ). Its not that important in case of bash (or any POSIX compatible shell) as it has same effect as just calling sh -c STRING except that eval is inbuilt on bash so it should be bit faster. Actual need depends on your coding style, but in most cases you can void use of it and I would personally recommend not to use it to make code more clear to read.


----------



## ta0kira (Apr 21, 2013)

The main reason to use eval is because special characters aren't interpreted if they're contained within a string. e.g.:
	
	



```
$ cmd='hello | tr "[:lower:]" "[:upper:]"'
$ echo $cmd
[B]hello | tr "[:lower:]" "[:upper:]"[/B]
$ eval echo $cmd
[B]HELLO[/B]
```
This is also useful if you want to specify a variable name using another variable. That's what the rc system uses to expand variables from /etc/rc.conf.
	
	



```
$ var=something
$ something=hello
$ eval echo \$$var
[B]hello[/B]
```
It can also be used to expand a file descriptor for redirection:
	
	



```
$ fd=10
$ eval exec "$fd>&1"
```
The special characters aren't interpreted in strings by default because 1) that would be a major security problem, 2) usually you really mean to use those characters as text. For example:
	
	



```
$ read -p 'what is your name? ' name
[B]what is your name? [U]kevin; followed-by-a-nasty-command[/U][/B]
$ echo $name
[B]kevin; followed-by-a-nasty-command[/B]
$ eval echo $name
[B]kevin
-bash: followed-by-a-nasty-command: command not found[/B]
```
It's useful for a lot of things, but some people are fervently against it. As long as the author of what you're evaling also has access to the UID that's performing the eval, it's not that big of a deal. In other words, don't run a script as root that evals input provided by a normal (or unauthenticated) user. It's really no worse than using . to source another file, or even calling a shell script in the first place.

Kevin Barry


----------



## fonz (Apr 21, 2013)

ta0kira said:
			
		

> It's useful for a lot of things


In fact, we had a question here just a few months ago. The solution was... (drum roll) "Use eval."


----------



## yom (Apr 22, 2013)

Another use:

```
eval $(stat -s myfile)
```
then use the variables returned from `stat -s`


----------



## fullauto (Apr 22, 2013)

Thank you all. They were all very helpful.


----------

