expansions

eval

Concatenates its arguments into a string and executes it as a shell command, going through parsing, expansion, and execution twice. Powerful for building dynamic commands, dangerous with untrusted input.

eval [ARG ...]

Common flags / operators

Flag / Operator Purpose
(no options) eval takes only arguments
exit status Status of the executed command, or 0 if empty
double expansion Arguments are re-parsed after concatenation
printf %q Use %q to safely quote args for eval

Examples

var=x; name=var; eval echo \$$name

Indirect variable read — prints x.

eval "$(ssh-agent -s)"

Import env-var assignments printed by another command.

cmd=$(printf '%q ' ls -la /tmp); eval "$cmd"

Reassemble safely-quoted command and run it.

for i in 1 2 3; do eval "v$i=$i"; done

Dynamically name variables (prefer arrays instead).

Gotcha

'eval' with any user-provided text is a code-injection vulnerability — always quote with printf '%q' first, or better yet use arrays / namerefs. Two rounds of expansion means every $ and ` reactivates.

Related

← All Bash builtins · Linux commands