Simply think of eval as "evaluating your expression one additional time before execution"
eval echo \${$n}
becomes echo $1
after the first round of evaluation. Three changes to notice:
\$
became $
(The backslash is needed, otherwise it tries to evaluate ${$n}
, which means a variable named {$n}
, which is not allowed)$n
was evaluated to 1
eval
disappearedIn the second round, it is basically echo $1
which can be directly executed.
So eval <some command>
will first evaluate <some command>
(by evaluate here I mean substitute variables, replace escaped characters with the correct ones etc.), and then run the resultant expression once again.
eval
is used when you want to dynamically create variables, or to read outputs from programs specifically designed to be read like this. See http://mywiki.wooledge.org/BashFAQ/048 for examples. The link also contains some typical ways in which eval
is used, and the risks associated with it.