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