eval
Execute constructed commands or expressions
TLDR
Call echo with the "foo" argument
Set a variable in the current shell
SYNOPSIS
eval [argument …]
DESCRIPTION
The eval command is a powerful shell built-in utility that executes strings provided as arguments by interpreting them as shell commands. It concatenates all given arguments, separating them with single spaces, forming a single string. This string is then parsed and executed exactly as if it had been typed directly into the interactive shell or read from a script.
Eval is particularly useful for scenarios involving dynamic command generation, such as constructing commands from variables or user input while preserving proper quoting and expansion. For instance, it enables indirect variable expansion or running commands stored in variables. A common pattern is eval "$cmd" where $cmd holds a command string.
However, its strength lies in its ability to bypass normal shell parsing stages, re-parsing the string through word splitting, globbing, and expansions anew. This flexibility comes at a cost: eval can introduce subtle bugs if quoting is mishandled and poses severe security risks with untrusted data, potentially enabling command injection attacks.
In modern scripting, alternatives like shell functions, arrays, or printf with read are preferred for safer dynamic execution.
CAVEATS
Eval is inherently unsafe for untrusted input due to command injection risks. Mishandled quoting leads to unexpected expansions. Use sparingly; prefer structured alternatives like functions or process substitution.
EXAMPLES
eval "echo Hello World"
Output: Hello World
files=(*.txt); eval "ls \"${files[@]}\""
Lists .txt files with proper quoting.
cmd='date'; eval "$cmd"
Runs the command in $cmd.
SAFER ALTERNATIVES
Use shell arrays: args=(ls -l); "${args[@]}"
Or functions: define dynamically instead of strings.
HISTORY
Originated in the Bourne shell (1977) by Stephen Bourne. Included in POSIX.1-1992 as a standard shell command. Evolved with shells like Bash (1989), maintaining core behavior for portability.


