Bash - Eval

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.
 
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.
 
The main reason to use eval is because special characters aren't interpreted if they're contained within a string. e.g.:
Code:
$ 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.
Code:
$ var=something
$ something=hello
$ eval echo \$$var
[B]hello[/B]
It can also be used to expand a file descriptor for redirection:
Code:
$ 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:
Code:
$ 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
 
Back
Top