Why eval Is Risky and Safer Alternatives

Su Suriya Ravichandran Updated 06 Dec 2026
13 min read ·Lesson 157 of 205

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 the hello world example showed.
  • Errors appear far from their cause. A syntax error inside an eval string is reported at the eval line, 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 eval line 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 VALUE assigns the formatted value to the variable called NAME.
  • declare -n ref=NAME (also local -n in a function) makes ref a name reference: reading or assigning ref reads or assigns the variable it points to. unset -n ref removes the reference itself, not the target.
  • ${!name} reads the variable whose name is stored in name (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 for eval, 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. conf holds the default values, and rule holds 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_REMATCH holds 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 as PATH are refused rather than silently ignored, so a typing mistake in the file is reported.
  • Checking the value. The value must match its rule. APP_HOST allows letters, digits, dots, hyphens and spaces; GREETING allows 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_NAME must 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 %q when exact display matters. GREETING is printed with printf '%s\n', so its $USER and $(date) stay text.
  • Dispatch. The action name selects a function only if declare -F finds action_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

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Why eval Is Risky and Safer Alternatives and get answers drawn from it.

Signed-in readers only.