What Is Shell Injection and How It Happens Step by Step
Shell injection turns data into commands. See five ways it happens in real scripts, from unquoted variables to eval and ssh, and how to spot each one.

Take a script that deletes a user's cache: rm -rf /var/cache/app/$1. Run it with the argument ../../.. and it deletes far more than a cache. Nobody typed a malicious command; the data was not treated as data. Shell injection is that mistake in many forms, and recognizing the five common shapes is most of the defense. This post shows them. The fixes are collected in preventing command injection in Bash scripts, and the topic as a whole is in shell script security.
Behavior is that of Bash 5.2 on Debian 13; other POSIX shells parse the same way.
Why it happens: parse first, then run
A shell does not pass your text straight to a program. It first splits the line into words, expands variables, command substitutions and globs, and only then runs the result. Whatever a variable contains takes part in that process unless it is quoted. This is how a shell script and a SQL query share a weakness: both build code out of strings.
1. The unquoted variable
name="report 2025.txt"
rm $nameThis runs rm report 2025.txt with two arguments, and a value containing * would expand to every file in the directory. Quoting, rm -- "$name", passes one argument. ShellCheck flags it as SC2086.
2. eval
read -r field
eval "echo \$$field"The intent is to print the variable whose name the user typed. The input HOME; cat /etc/passwd makes the string echo $HOME; cat /etc/passwd and eval runs both. eval exists to parse text as code, so any outside data in it is injection by design. Safer forms are in avoiding eval and source.
3. sh -c with a built string
sh -c "grep $pattern $file"
find . -name '*.log' -exec sh -c "gzip $1" _ {} \;Inside the double quotes the outer shell has already substituted the variable into the string, which the inner shell parses again. Pass data as positional parameters instead, and keep the script text fixed: sh -c 'grep -- "$1" "$2"' _ "$pattern" "$file". The same mistake appears when a program accepts a command string, as with system() in C, os.system in Python and backticks in Perl and Ruby.
4. ssh and other remote shells
ssh host "ls /srv/$dir"The string you pass is joined and handed to the remote user's shell, so it is parsed on the far side after your local shell parsed it once. A value with spaces or semicolons is interpreted remotely. Quote each argument for the remote shell with printf '%q': ssh host "ls $(printf '%q' "/srv/$dir")", or feed the data through standard input.
5. Option injection
filename="-rf"
rm "$filename"Even a correctly quoted value can be read as an option by the program. Filenames from outside, such as an upload or a directory listing, may begin with a dash. The end-of-options marker -- tells most programs that everything after it is an operand, and a ./ prefix has the same effect. Handling untrusted filenames goes through this in depth.
Where the data comes from
| Source | Example |
|---|---|
| Arguments and environment | $1, $USER_INPUT |
| Filenames | Uploads, ls output, archive members |
| Network | HTTP parameters, API responses, DNS names |
| Other programs' output | git log messages, docker ps names |
Config files read with source | A .env any user can write |
The question to ask of each line is whether the value could contain a space, quote, semicolon, dollar sign, backtick, newline or leading dash, and what happens if it does.
Seeing the second command run
The mechanism is easiest to believe once you have watched it. A value that contains a semicolon is harmless as an argument and dangerous when it is pasted into text that a shell then parses. The two runs below pass the same hostile string to ls twice: once spliced into a string for sh -c, and once as a separate argument. The payload is an echo, so nothing is damaged. Output is from dash and GNU coreutils on Debian 13.
f='x; echo INJECTED'
sh -c "ls $f" 2>&1 | head -n 3
sh -c 'ls -- "$1"' _ "$f" 2>&1 | head -n 2ls: cannot access 'x': No such file or directory
INJECTED
ls: cannot access 'x; echo INJECTED': No such file or directory
In the first run the shell read the string as two commands: a failing ls x, and then echo INJECTED. The second run handed the value to the script as $1, so it reached ls as one filename and nothing else ran. The difference is where the data travels. In the first, it was part of the program text. In the second, it was a parameter of an already-parsed program. Every fix in this family is a way to keep data on the second path.
What an attacker gets from each hole
The impact depends on who runs the script. A script run by a developer on their laptop gives the attacker that developer's files and credentials. One that runs from cron as root gives the whole machine. A script in a CI job gives the pipeline's secrets and deploy keys, which is why shell injection in build scripts is a supply-chain problem and not only a server problem. When you triage a finding, ask three questions: where does the data come from, who controls it, and what privilege does the script run with. A hole that needs a hostile filename in a directory only you write to is a bug. The same hole in an upload directory or a CI job that checks out untrusted pull requests is an incident waiting for a visitor.
Option injection needs no shell at all
The fifth case in the list does not involve parsing. A value that starts with a dash is read as an option by almost every command, even when it is quoted perfectly. A filename like -rf passed to rm, or a pattern like --include=x passed to grep, changes what the command does. The remedy is the double dash that ends option parsing, put before any operand that came from outside: rm -- "$file". Commands that lack the double dash convention are the dangerous ones, so prefix relative paths with ./, which makes a leading dash impossible. For tar and git, which have options that run other programs, validate the value against an allow-list instead.
Limits of the lesson
A script that only your own account runs, on values you typed, is not a security boundary, but a bug that deletes the wrong directory is still a bug. Injection matters most when the script runs with more privilege than its caller or accepts data from outside, such as a CGI script, a webhook handler, a cron job reading a shared directory or a CI step using a pull request title. The weakness class is CWE-78, and the Bash parsing rules are in the manual's shell operation section.


