Why eval Is Risky and Safer Alternatives
eval is a Bash built-in that takes its arguments, joins them into one string, and then runs that string as Bash code. It gives a script a second round of parsing: everything that was data after the first round becomes code in the second.
That power is the reason eval exists, and also the reason it is risky. Whenever any part of the string comes from outside the script, such as an argument, a file, a variable set by the user or the output of a command, that part can contain ;, $( ), quotes or newlines, and eval will run it. Lesson 155 called this command injection. This lesson explains exactly what eval does, where people reach for it, and the built-in Bash features that solve the same problems without parsing data as code.
Understanding the Concept
Normally Bash parses a command line once. It finds words, operators and quotes, then expands variables. The results of expansion are never parsed again, which is why a variable containing ; does not start a new command:
cmd='echo one; echo two'
$cmd
eval "$cmd"
one; echo two
one
two
Without eval, $cmd was split into the words echo, one;, echo and two, and echo printed them. The ; was just a character. With eval, the value was parsed as a script, so ; separated two commands.
The second parse also performs a second round of expansions:
x='$HOME'
echo "$x"
eval echo "$x"
$HOME
/root
The variable held the literal text $HOME. eval built the string echo $HOME, parsed it, and expanded $HOME. This "double expansion" is what people usually want from eval, and it is exactly what makes it dangerous: every $, backtick and quote in the data gets a second chance to mean something.
eval Joins Its Arguments First
eval joins its arguments with single spaces before parsing. Quoting the arguments to eval therefore does not protect the value inside them:
a='hello world'
eval echo $a
eval echo "$a"
eval 'echo "$a"'
hello world
hello world
hello world
In the first two lines, the value was inserted into the code string, and the second parse split it again, so the three spaces collapsed to one. Only the third form kept the spaces, because the code string echo "$a" contains the variable name, not its value; the value is expanded during the second parse and quoted there. This is the single rule that makes eval safe when you must use it: pass names and fixed code to eval, never values.
Why eval Is Risky
Data Becomes Code
A common reason to use eval is to assign to a variable whose name is stored in another variable:
name=color; value='red'
eval "$name=\$value"
echo "color=$color"
value='blue; echo INJECTED'
eval "$name=$value"
echo "color=$color"
color=red
INJECTED
color=blue
The first eval is written carefully: the value is referenced as \$value, so only the name color is inserted into the code. The second forgets the backslash, so the value is inserted, and the ; echo INJECTED part of the value runs as a command.
Even the careful version is unsafe when the name comes from outside the script:
name='x=1; echo INJECTED-NAME; y'
eval "$name=\$value"
INJECTED-NAME
Problems That Are Hard to See
The risks of eval are not limited to attacks:
- Quoting becomes two-level. Every value has to be correct for two parses. Spaces, quotes and
$in ordinary data silently change, as thehello worldexample showed. - Errors appear far from their cause. A syntax error inside an
evalstring is reported at theevalline, not where the bad string was built. - Tools cannot help. Static checkers such as ShellCheck (lesson 162) cannot analyze code that exists only as a string at run time.
- Reviewers cannot see the code. To know what an
evalline does, a reader has to work out every possible value of the string.
Almost every task that seems to need eval has a direct Bash feature that keeps data as data. The sections below show these replacements.
Alternative 1: Arrays for Building Commands
People often build a command in a string and run it with eval so that quoted arguments survive. An array does this without a second parse (lesson 97). In this example, an empty file named my file.txt exists in the current folder:
opts=(-c)
file='my file.txt'
cmd=(wc "${opts[@]}" -- "$file")
"${cmd[@]}"
printf '%q ' "${cmd[@]}"; echo
0 my file.txt
wc -c -- my\ file.txt
Each array element is one argument, so the file name with a space stays one argument. You can add options conditionally with cmd+=(-v), and print the command for a log with printf '%q ', which shows exactly how it would be typed.
Alternative 2: printf -v, Namerefs and Indirect Expansion
For variables whose names are chosen at run time, Bash has three built-in tools:
name=color
printf -v "$name" '%s' 'green'
echo "printf -v: $color"
declare -n ref=$name
ref='purple'
echo "nameref: $color"
unset -n ref
echo "indirect: ${!name}"
printf -v: green
nameref: purple
indirect: purple
printf -v NAME FORMAT VALUEassigns the formatted value to the variable called NAME.declare -n ref=NAME(alsolocal -nin a function) makesrefa name reference: reading or assigningrefreads or assigns the variable it points to.unset -n refremoves the reference itself, not the target.${!name}reads the variable whose name is stored inname(indirect expansion).
The values never pass through a parser. These tools do still treat the name specially, so a name from outside the script must be validated. Bash rejects some bad names on its own:
name='x=1; echo INJECTED-NAME; y'
printf -v "$name" '%s' v; echo "status $?"
declare -n r="$name"; echo "status $?"
demo.sh: line 8: printf: `x=1; echo INJECTED-NAME; y': not a valid identifier
status 2
demo.sh: line 9: declare: `x=1; echo INJECTED-NAME; y': invalid variable name for name reference
status 1
(The messages name the script, demo.sh, and the line where each command stood in it.)
But names with array subscripts, such as a[$(command)], are accepted and can run commands (lesson 155). Validate every name with an allowlist before using it:
valid_name() { [[ $1 =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; }
for n in color 'x=1; echo' '2abc' 'a[$(id)]' _ok; do
if valid_name "$n"; then echo "ok: ${n@Q}"; else echo "bad: ${n@Q}"; fi
done
ok: 'color'
bad: 'x=1; echo'
bad: '2abc'
bad: 'a[$(id)]'
ok: '_ok'
To list variables that share a prefix, use ${!prefix@} instead of building names in a string:
app_port=80 app_host=web1 other=1
for v in "${!app_@}"; do echo "$v=${!v}"; done
app_host=web1
app_port=80
Alternative 3: Associative Arrays for Dynamic Keys
Often the real need is not a variable with a dynamic name, but a lookup table: a value stored under a key that comes from data. An associative array (lesson 102) is the right tool, because its keys are always data and can contain any characters:
declare -A cfg
key='any key; $(echo hi)'
cfg[$key]='value'
for k in "${!cfg[@]}"; do printf 'key=%q\n' "$k"; done
key=any\ key\;\ \$\(echo\ hi\)
The key was stored exactly as given; nothing ran. Storing settings in one associative array is also tidier than creating many global variables, and it keeps user-chosen names from overwriting important variables such as PATH.
Alternative 4: Dispatching to Functions Without eval
Scripts with subcommands sometimes run eval "cmd_$1". Any text after the command name is then executed:
cmd_start() { echo "starting"; }
sub='start; echo INJECTED-DISPATCH'
eval "cmd_$sub"
starting
INJECTED-DISPATCH
Bash can call a function whose name is held in a variable directly, because a command name produced by expansion is not parsed again. Check that the function exists with declare -F first:
cmd_start() { echo "starting"; }
cmd_stop() { echo "stopping"; }
run() {
local sub=$1
if declare -F "cmd_$sub" > /dev/null; then "cmd_$sub"; else echo "unknown command: ${sub@Q}" >&2; return 2; fi
}
run start; run stop; run 'start; echo INJECTED'; echo "status $?"
starting
stopping
unknown command: 'start; echo INJECTED'
status 2
A case statement that lists the allowed subcommands is an equally good choice and makes the list of commands visible in one place.
Alternative 5: Parsing Data Instead of Sourcing It
Configuration files written as KEY=value lines are often loaded with source (lesson 95) or with eval on each line. Both run the file as Bash code. Consider this file, evil.conf:
APP_NAME=shop; echo INJECTED-BY-SOURCE
APP_PORT=$(echo INJECTED-BY-SUBST >&2; echo 80)
PATH=/tmp/evil
UNKNOWN_KEY=1
not a setting
Sourcing it in a subshell shows what would happen:
( source ./evil.conf 2>&1; echo "PATH is now: $PATH" )
INJECTED-BY-SOURCE
INJECTED-BY-SUBST
./evil.conf: line 5: not: command not found
PATH is now: /tmp/evil
Two commands ran, an unknown line was executed as a command, and PATH was replaced, which would make every later command name look in /tmp/evil. source is acceptable only for files that are exactly as trusted as the script itself. For files that users or other programs can write, parse the lines as data. The complete example below does that.
When eval Is Acceptable
eval is not forbidden; it is a tool for the rare cases where generating code is the point. Two situations are common:
- Trusted tools that print shell code, for example
eval "$(ssh-agent -s)". The tool is designed to produce code foreval, and it does not include outside data. - Code you generate with every value quoted, using
printf '%q'or${var@Q}:
val=$'it\'s $(echo RUN) "x"'
printf -v q '%q' "$val"
eval "safe=$q"
printf '%s\n' "$safe"
eval "unsafe=\"$val\""
printf '%s\n' "$unsafe"
it's $(echo RUN) "x"
it's RUN x
With %q, the second parse produced exactly the original value. Without it, the command substitution ran and the quotes disappeared. Even when eval is justified, keep the string short, build it in one place, and quote every value with %q.
A Complete Example: A Deploy Script with a Safe Config Loader
deploy.sh reads settings from a configuration file and runs one action. It uses no eval and no source: the file is parsed as data, every key must be known, every value must match a rule, and the action name is checked against the functions that exist.
The normal configuration file, deploy.conf, uses a few common styles: spaces around =, double quotes, single quotes and a comment:
# deploy.conf: settings for deploy.sh
APP_NAME = shop-api
APP_PORT=8080
APP_HOST="web 1.example.com"
GREETING='Hello $USER, today is $(date)'
RETRIES=3
#!/usr/bin/env bash
# deploy.sh: read settings without eval or source, then run an action
# usage: deploy.sh [-c CONFIG] ACTION (ACTION: show, check, start)
set -uo pipefail
declare -A conf=( [APP_NAME]='' [APP_PORT]=80 [APP_HOST]=localhost [GREETING]='Hello' [RETRIES]=1 )
declare -A rule=( [APP_NAME]='^[a-z][a-z0-9-]{0,30}$' [APP_PORT]='^[0-9]{1,5}$'
[APP_HOST]='^[A-Za-z0-9. -]{1,253}$' [GREETING]='^.{0,80}$' [RETRIES]='^[0-9]$' )
die() { printf '%s: %s\n' "${0##*/}" "$1" >&2; exit 2; }
load_config() {
local file=$1 line key value n=0 errors=0
[[ -r $file ]] || die "cannot read config file: ${file@Q}"
while IFS= read -r line || [[ -n $line ]]; do
(( n++ ))
line=${line%$'\r'}
[[ $line =~ ^[[:space:]]*(#|$) ]] && continue
if [[ ! $line =~ ^[[:space:]]*([A-Z_][A-Z0-9_]*)[[:space:]]*=[[:space:]]*(.*)$ ]]; then
printf '%s:%d: not a KEY=VALUE line: %s\n' "$file" "$n" "${line@Q}" >&2; (( errors++ )); continue
fi
key=${BASH_REMATCH[1]} value=${BASH_REMATCH[2]}
value=${value%"${value##*[![:space:]]}"} # trim trailing spaces
if [[ $value =~ ^\"(.*)\"$ || $value =~ ^\'(.*)\'$ ]]; then
value=${BASH_REMATCH[1]} # remove one pair of quotes
fi
if [[ ! -v rule[$key] ]]; then
printf '%s:%d: unknown key: %s\n' "$file" "$n" "$key" >&2; (( errors++ )); continue
fi
if [[ ! $value =~ ${rule[$key]} ]]; then
printf '%s:%d: invalid value for %s: %s\n' "$file" "$n" "$key" "${value@Q}" >&2; (( errors++ )); continue
fi
conf[$key]=$value
done < "$file"
(( errors == 0 )) || die "$errors problem(s) in ${file@Q}"
[[ -n ${conf[APP_NAME]} ]] || die 'APP_NAME is required'
(( 10#${conf[APP_PORT]} >= 1 && 10#${conf[APP_PORT]} <= 65535 )) || die 'APP_PORT must be 1-65535'
}
action_show() {
local key keys
mapfile -t keys < <(printf '%s\n' "${!conf[@]}" | LC_ALL=C sort)
for key in "${keys[@]}"; do
printf '%-9s = %s\n' "$key" "${conf[$key]}"
done
}
action_check() {
printf 'would connect to %q on port %d (%d attempt(s))\n' "${conf[APP_HOST]}" "$((10#${conf[APP_PORT]}))" "${conf[RETRIES]}"
}
action_start() {
printf '%s\n' "${conf[GREETING]}"
printf 'starting %s\n' "${conf[APP_NAME]}"
}
config=deploy.conf
if [[ ${1-} == -c ]]; then
(( $# >= 2 )) || die 'option -c needs a file'
config=$2; shift 2
fi
(( $# == 1 )) || die 'usage: deploy.sh [-c CONFIG] show|check|start'
action=$1
load_config "$config"
# Dispatch only to functions that exist, never with eval
declare -F "action_$action" > /dev/null || die "unknown action: ${action@Q}"
"action_$action"
How It Works
- Two associative arrays describe the settings.
confholds the default values, andruleholds one regular expression per allowed key. Adding a setting means adding one entry to each. - Reading lines.
IFS= read -r line || [[ -n $line ]]reads every line exactly, including a last line without a newline (lesson 114).${line%$'\r'}removes a Windows line ending. Blank lines and comments are skipped. - Splitting key and value. One regular expression checks the whole line: optional spaces, a key made of capital letters, digits and underscores, optional spaces,
=, optional spaces, then the value.BASH_REMATCHholds the two parts. The next line trims trailing spaces, and one pair of matching double or single quotes is removed. Quotes are just characters here; nothing inside them is expanded. - Checking the key.
[[ -v rule[$key] ]]tests whether the key exists in the rule table. Because the key has already matched^[A-Z_][A-Z0-9_]*$, it cannot contain a subscript trick. Unknown keys such asPATHare refused rather than silently ignored, so a typing mistake in the file is reported. - Checking the value. The value must match its rule.
APP_HOSTallows letters, digits, dots, hyphens and spaces;GREETINGallows any text up to 80 characters, because it is only ever printed. Problems are counted, every problem is reported with its line number, and the script stops if there was at least one. - Final checks.
APP_NAMEmust be set, and the port must be in range.10#makes Bash read the digits as a decimal number even with leading zeros (lesson 73). - Using the settings. Values are always used with quotes, or printed with
%qwhen exact display matters.GREETINGis printed withprintf '%s\n', so its$USERand$(date)stay text. - Dispatch. The action name selects a function only if
declare -Ffindsaction_NAME. Anything else is refused and shown with@Q.
Running the Complete Example
./deploy.sh show; echo "status $?"
./deploy.sh check
./deploy.sh start
APP_HOST = web 1.example.com
APP_NAME = shop-api
APP_PORT = 8080
GREETING = Hello $USER, today is $(date)
RETRIES = 3
status 0
would connect to web\ 1.example.com on port 8080 (3 attempt(s))
Hello $USER, today is $(date)
starting shop-api
The spaces around = were accepted, both kinds of quotes were removed, and the greeting kept $USER and $(date) as text. %q in the check action makes the space in the host name visible.
The same script refuses an injected action and the hostile evil.conf file shown earlier:
./deploy.sh 'show; echo INJECTED'; echo "status $?"
./deploy.sh -c evil.conf show; echo "status $?"
deploy.sh: unknown action: 'show; echo INJECTED'
status 2
evil.conf:1: invalid value for APP_NAME: 'shop; echo INJECTED-BY-SOURCE'
evil.conf:2: invalid value for APP_PORT: '$(echo INJECTED-BY-SUBST >&2; echo 80)'
evil.conf:3: unknown key: PATH
evil.conf:4: unknown key: UNKNOWN_KEY
evil.conf:5: not a KEY=VALUE line: 'not a setting'
deploy.sh: 5 problem(s) in 'evil.conf'
status 2
Where source ran two commands and replaced PATH, the parser ran nothing and reported all five problems with their line numbers. Invalid ranges and missing files are reported too:
printf 'APP_NAME=x\nAPP_PORT=70000\n' > big.conf
./deploy.sh -c big.conf check; echo "status $?"
./deploy.sh -c nope.conf show; echo "status $?"
deploy.sh: APP_PORT must be 1-65535
status 2
deploy.sh: cannot read config file: 'nope.conf'
status 2