Is it always safe to use `eval echo`?

Counterexample:

DANGEROUS=">foo"
eval echo $DANGEROUS

The arbitrary arguments to echo could have done something more nefarious than creating a file called "foo".


@Celada has provided an excellent answer. To demonstrate eval is really evil, here's something more nefarious than creating a file called "foo":

DANGEROUS='$(rm foo)'
eval echo "$DANGEROUS"

And of course there can be something more nefarious than something more nefarious than creating a file called "foo".


No, it is not always safe. An eval could execute any command.

A safe command, like this (the date is not executed as it is inside single quotes):

$ echo '$(date)'
$(date)

Becomes dangerous if used with eval:

$ eval echo '$(date)'
Sat Dec 24 22:55:55 UTC 2016

Of course, date could be any command.

One way to improve this is to additionally quote the arguments to eval:

$ eval echo '\$(date)'
$(date)

But it is usually difficult to correctly quote twice an expression.

And it becomes impossible to control the correct quoting if the expression could be set by an external attacker, like:

$ var='$(date);echo Hello!'
$ eval echo "$var"
Sat Dec 24 23:01:48 UTC 2016
Hello!

Tags:

Bash

Echo