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
declare / typeset / readonly
Declares variables with attributes: arrays, associative arrays, integers, readonly, lowercase/uppercase, exported. 'readonly' is a shortcut for 'declare -r' that locks a variable so it cannot be reassigned or unset for the lifetime of the shell.
source (.)
Executes FILE in the CURRENT shell (no subshell), so variables, functions, and aliases defined in it persist. Contrast with 'bash file' which runs in a child process — its side effects vanish when it exits.
set (options)
Changes shell option flags and/or replaces positional parameters. The 'safer bash' idiom 'set -euo pipefail' is the most common use — it turns on error-exit, unset-variable-error, and pipeline failure propagation.