Avoiding Command Injection in Shell Scripts

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

Command injection happens when data that was meant to be a plain value ends up being parsed as shell code. A file name, a search term or a form field contains characters such as ;, $( ), quotes or newlines, the script pastes that value into a piece of code, and the shell (or another interpreter such as awk or sed) runs part of the value as a command.

The cause is almost always the same: building code by joining strings. The cure is also always the same: keep code and data separate. Code is written by you, in single quotes or in the script itself. Data travels separately, as arguments, environment variables or standard input, so no interpreter ever reads it as code.

All examples in this lesson use harmless payloads such as echo INJECTED so you can try them safely. In a real attack, the same position would hold a command that deletes files, steals credentials or opens a remote connection.

Understanding the Concept

When Bash runs a command, it first parses the text: it finds the command name, the arguments, the operators such as ; and |, the quotes and the expansions. Only after parsing does it expand variables. This order is what protects ordinary scripts:

input='a.txt; echo INJECTED'
cat -- "$input"
cat: 'a.txt; echo INJECTED': No such file or directory

The ; inside $input is never seen by the parser, because the variable is expanded after parsing, and the double quotes keep the value as one word. cat simply receives a strange file name.

Injection appears when a value is expanded and then parsed again. Every place that parses a string as code is a potential injection point:

Code that parses a stringTypical mistake
evaleval "echo $input"
bash -c, sh -cbash -c "cat $input"
ssh host COMMANDssh host "grep $term /var/log/app.log"
find -exec sh -c, xargs sh -csh -c 'echo {}'
awk program textawk "/$term/"
sed script textsed "s/x/$input/"
arithmetic(( n = input + 1 ))
variable names${!input}, printf -v "$input", declare "$input=..."
source, .source "$user_supplied_file"

The Classic Case: bash -c and eval

In the following examples, the file a.txt contains the single line hello.

input='a.txt; echo INJECTED'
bash -c "cat $input"
hello
INJECTED

The double-quoted string was expanded first, producing the code cat a.txt; echo INJECTED, and then the new Bash process parsed it. cat printed the file, and the injected command ran too. eval behaves in exactly the same way, because it also parses its argument as code:

eval "echo Hello $input"
Hello a.txt
INJECTED

The Fix: Pass Data as Arguments

bash -c and sh -c accept arguments after the code string. The first one becomes $0 (by convention a short name such as _), and the rest become $1, $2 and so on. The code is written in single quotes, so nothing is expanded when it is built:

bash -c 'cat -- "$1"' _ "$input"
cat: 'a.txt; echo INJECTED': No such file or directory

The value arrives as $1, an ordinary argument that is never parsed. This pattern, fixed code in single quotes plus data as arguments, is the most important technique in this lesson. For eval, the best fix is usually not to use it at all; lesson 157 shows the alternatives.

Injection Through File Names

File names are data that other people can choose. Anyone who can create a file in a folder your script processes can choose a name containing quotes and semicolons. Consider a folder with a file whose name is x"; echo "INJECTED-BY-NAME:

find . -name 'x*' -exec sh -c 'echo "found: {}"' \;
found: ./x
INJECTED-BY-NAME

find pasted the file name into the code string in place of {}, so the quote in the name closed the string and the rest became a new command. The fix is again to pass the name as an argument:

find . -name 'x*' -exec sh -c 'echo "found: $1"' _ {} \;
found: ./x"; echo "INJECTED-BY-NAME

{} now stands alone as a separate argument, which find passes directly. With + instead of \;, many names are passed at once, and the code loops over them with for f; do ...; done. The same pattern works for xargs -0 sh -c '...' _. Never put {} inside the code string.

Injection into awk and sed

awk and sed are programming languages with their own parsers, and they can run commands: awk has system() and sed (GNU) has the e command. Building their programs from user data is just as dangerous as building shell code.

awk: Use -v or ENVIRON

printf 'line one\nline two\n' > log.txt
term='x"; system("echo INJECTED-AWK"); print "'
awk "/one/ { print \"$term\" }" log.txt
x
INJECTED-AWK

The value closed the string in the awk program and added a system() call. Passing the value as an awk variable keeps it as data:

awk -v t="$term" '/one/ { print t }' log.txt
T="$term" awk '/one/ { print ENVIRON["T"] }' log.txt
x"; system("echo INJECTED-AWK"); print "
x"; system("echo INJECTED-AWK"); print "

The two methods differ in one detail. -v processes backslash escapes in the value, while ENVIRON passes it exactly as it is:

awk -v t='a\tb' 'BEGIN { print t }'
T='a\tb' awk 'BEGIN { print ENVIRON["T"] }'
a	b
a\tb

When the value must arrive byte for byte, for example a search term, use ENVIRON. Also prefer index($0, t) (literal text) to $0 ~ t (regular expression) when the user means plain text.

sed: Avoid Data in the Script

sed has no clean way to pass a value as data. With GNU sed, an attacker who controls the whole script can run commands with the e command:

user='1e echo INJECTED-SED'
sed "$user" log.txt
INJECTED-SED
line one
line two

Never let user input become a whole sed script. When user data must go into the replacement part of s///, escape the three characters that are special there (0, &` and the delimiter):

repl='a/b&c\d'
esc=$(printf '%s' "$repl" | sed 's/[\/&\\]/\\&/g')
echo "path X here" | sed "s/X/$esc/"
path a/b&c\d here

For anything more complex, use Bash parameter expansion (${line//"$old"/"$new"}, lesson 152) or awk with ENVIRON, which need no escaping.

Injection Through Arithmetic and Variable Names

Bash evaluates the contents of variables used in arithmetic, and array subscripts inside those contents can contain command substitutions (lesson 154). The same happens wherever Bash treats a value as a variable name:

userkey='a[$(echo INJECTED-INDIRECT >&2)]'
echo "${!userkey}"
vname='x[$(echo INJECTED-PRINTFV >&2)]'
printf -v "$vname" '%s' hi
key2='a[$(echo INJECTED-DECLARE2 >&2)]'
declare "$key2=5"
INJECTED-INDIRECT

INJECTED-PRINTFV
INJECTED-DECLARE2

Each command ran a command hidden in the "name". The defence is to validate before use:

  • numbers: [[ $n =~ ^[0-9]+$ ]] before any arithmetic;
  • variable names: [[ $name =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] before ${!name}, printf -v, declare or declare -n;
  • keys for lookups: use an associative array (lesson 102), whose keys are always data: ${config[$key]} is safe for any $key.

Option Injection

A value that starts with - can be read as an option instead of an argument. It is not command injection in the strict sense, but it changes what a command does, and options such as find -exec, tar --checkpoint-action or rsync -e can run commands. Two habits prevent it:

term='--help'
grep "$term" log.txt
grep -c -e "$term" -- log.txt
Usage: grep [OPTION]... PATTERNS [FILE]...
0

In the first command, grep took the search term as its --help option. In the second, -e marks the next argument as the pattern, and -- ends option parsing before the file names. Use -- with every command that accepts it, and the command's own "this is a value" option where one exists (grep -e, printf '%s').

Format Strings

printf treats its first argument as a format. If user data is used as the format, its % sequences are interpreted:

name='100%s done %s'
printf "$name\n"
printf '%s\n' "$name"
100 done 
100%s done %s

Bash's printf cannot run commands through a format, but the output is wrong and % sequences can make it fail. Always write the format yourself and pass data as arguments: printf '%s\n' "$value".

Running Commands Remotely with ssh

ssh host ARGS... does not pass separate arguments to the remote machine. It joins them with spaces into one string, and the remote shell parses that string. So even correctly quoted local variables are parsed again on the other side:

ssh web1 grep -c -- "$term" /var/log/app.log   # $term is parsed by the remote shell

The fix is to quote each value for the remote shell before joining. printf '%q' and ${var@Q} (lesson 152) both produce text that Bash parses back into exactly the original value:

arg="it's \$(touch PWNED) a test"
printf -v q '%q' "$arg"
echo "$q"
bash -c "printf '%s\n' $q"
ls PWNED
it\'s\ \$\(touch\ PWNED\)\ a\ test
it's $(touch PWNED) a test
ls: cannot access 'PWNED': No such file or directory

Here bash -c stands in for the remote shell: the value came back unchanged, and no file was created. Without %q, the command substitution runs:

bash -c "printf '%s\n' \"$arg\""
ls PWNED
it's  a test
PWNED

A complete remote command therefore looks like this:

remote_cmd=$(printf 'grep -c -- %q %q' "$term" /var/log/app.log)
ssh -- "$host" "$remote_cmd"

%q output is designed for Bash. For values containing control characters, it uses the $'...' form, which very old sh implementations do not understand, so make sure the remote login shell is Bash, or restrict values to printable characters with an allowlist.

A Complete Example: A Safe Log Search Tool

log-search.sh searches recent .log files for a piece of text. It is designed to be called by other tools, for example a chat bot or a support web page, so the search text must be treated as pure data: no shell syntax, no regular expression, no options and no awk code. It also handles hostile file names and prints a copy-pasteable record of what was searched.

#!/usr/bin/env bash
# log-search.sh: search recent log files for a literal piece of text
# usage: log-search.sh TEXT [DAYS] [DIR]
#   TEXT  searched literally: no regex, no options, no shell syntax
#   DAYS  only logs modified in the last DAYS days (default 7)
#   DIR   folder to search (default: current folder)
set -uo pipefail

if (( $# < 1 || $# > 3 )); then
    echo "usage: ${0##*/} TEXT [DAYS] [DIR]" >&2
    exit 2
fi
text=$1 days=${2:-7} dir=${3:-.}

[[ -n $text ]] || { echo "${0##*/}: TEXT must not be empty" >&2; exit 2; }
[[ $days =~ ^[0-9]{1,4}$ ]] || { echo "${0##*/}: DAYS must be a number: ${days@Q}" >&2; exit 2; }
[[ -d $dir ]] || { echo "${0##*/}: not a folder: ${dir@Q}" >&2; exit 2; }
[[ $dir == /* || $dir == ./* || $dir == . ]] || dir=./$dir   # never starts with "-" or "name="

# A copy-pasteable record of exactly what was searched
printf 'search:'
printf ' %q' "${0##*/}" "$text" "$days" "$dir"
printf '\n'

# Collect file names safely: NUL-separated, never split or re-parsed
files=()
while IFS= read -r -d '' f; do
    files+=("$f")
done < <(find "$dir" -type f -name '*.log' -mtime -"$((10#$days))" -print0 | LC_ALL=C sort -z)

if (( ${#files[@]} == 0 )); then
    echo "no log files changed in the last $days day(s) under $dir"
    exit 1
fi

# The text reaches awk as data through the environment, never as program code
SEARCH_TEXT=$text awk '
    BEGIN { t = ENVIRON["SEARCH_TEXT"] }
    index($0, t) {
        n++
        line = length($0) > 80 ? substr($0, 1, 77) "..." : $0
        printf "%s:%d: %s\n", FILENAME, FNR, line
    }
    END {
        printf "%d matching line(s) in %d file(s)\n", n, ARGC - 1
        exit (n > 0 ? 0 : 1)
    }
' "${files[@]}"

How It Works

  • Validation first. The text must not be empty; DAYS must be 1 to 4 digits, so it is safe in $((10#$days)) and in the find argument; the folder must exist. Rejected values are shown with ${days@Q}, so hidden characters are visible in the error.
  • The folder is prefixed with ./ unless it is absolute or already starts with ./. This protects two places at once: find can never read the folder as an option (-delete, -exec), and awk can never read a path such as x=1.log/app.log as a variable assignment. awk treats any argument of the form name=value as an assignment rather than a file, which is an easy-to-miss form of option injection.
  • The record line uses printf ' %q' for each argument, so the logged command can be pasted back into a terminal and reproduces exactly the same search, even when the text contains quotes, spaces or $( ).
  • File names travel from find as NUL-separated data (-print0, sort -z, read -d '', lesson 112) into an array, and from the array to awk as separate arguments with "${files[@]}". At no point is a name pasted into code.
  • The search text reaches awk through the environment variable SEARCH_TEXT and is read with ENVIRON, so it is never part of the awk program and its backslashes are not interpreted. index($0, t) matches it as literal text, so .* means a dot and a star, not "anything".
  • The awk program is in single quotes and contains no shell variables at all. It prints each match with the file name and line number, shortens long lines, and exits with 1 when nothing matched, like grep.

Running the Complete Example

The logs folder contains app.log, a file with a space in its name (pay ments.log) whose content includes quotes and $( ), a file named x=1.log, and an old/archive.log that is 30 days old.

./log-search.sh ERROR 7 logs; echo "status $?"
search: log-search.sh ERROR 7 ./logs
./logs/app.log:2: 2026-11-24 10:02:13 ERROR db timeout after 30s
./logs/pay ments.log:1: 2026-11-24 09:59:00 ERROR payment "id=7"; retry $(scheduled)
./logs/x=1.log:1: ERROR in a file named like an awk assignment
3 matching line(s) in 3 file(s)
status 0

The file with a space was searched normally, the old archive was skipped because of -mtime -7, and x=1.log was read as a file, not as an awk assignment.

Search texts that would break a naive script are treated as plain text:

./log-search.sh '"; system("echo INJECTED"); "' 7 logs; echo "status $?"
./log-search.sh '$(scheduled)' 7 logs; echo "status $?"
./log-search.sh 'a\tb' 7 logs; echo "status $?"
./log-search.sh '-r' 7 logs; echo "status $?"
./log-search.sh '.*' 7 logs; echo "status $?"
search: log-search.sh \"\;\ system\(\"echo\ INJECTED\"\)\;\ \" 7 ./logs
0 matching line(s) in 3 file(s)
status 1
search: log-search.sh \$\(scheduled\) 7 ./logs
./logs/pay ments.log:1: 2026-11-24 09:59:00 ERROR payment "id=7"; retry $(scheduled)
1 matching line(s) in 3 file(s)
status 0
search: log-search.sh a\\tb 7 ./logs
./logs/pay ments.log:2: 2026-11-24 10:01:00 INFO a\tb literal backslash
1 matching line(s) in 3 file(s)
status 0
search: log-search.sh -r 7 ./logs
0 matching line(s) in 3 file(s)
status 1
search: log-search.sh .\* 7 ./logs
0 matching line(s) in 3 file(s)
status 1

The awk payload was searched for and simply not found; nothing ran. $(scheduled) matched the literal text in the payment log. a\tb matched a backslash followed by t, not a tab. -r was a search term, not an option, and .* matched only a literal dot and star.

Invalid arguments are refused before any file is touched:

./log-search.sh ERROR '1;echo INJECTED' logs; echo "status $?"
./log-search.sh ERROR 7 nope; echo "status $?"
./log-search.sh '' 7 logs; echo "status $?"
log-search.sh: DAYS must be a number: '1;echo INJECTED'
status 2
log-search.sh: not a folder: 'nope'
status 2
log-search.sh: TEXT must not be empty
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 Avoiding Command Injection in Shell Scripts and get answers drawn from it.

Signed-in readers only.