Quoting User Input Safely

Su Suriya Ravichandran Updated 06 Dec 2026
15 min read ·Lesson 156 of 205

User input is any value your script did not write itself: command-line arguments, answers typed at a prompt, lines read from a file, environment variables, file names found on disk, or text received from another program. Your script cannot predict what such a value contains. It may hold spaces, tabs, newlines, *, ?, quotes, backslashes, $( ), a leading -, or nothing at all.

Quoting user input safely means making sure that, at every point where the value is used, it stays one piece of data with exactly the characters the user gave. It must not be split into several words, expanded as a file name pattern, read as an option, treated as a pattern or a regular expression, or parsed as code by Bash or by another program.

Lesson 155 showed what happens when data becomes code. This lesson looks at the everyday side of the same problem: the quoting rules that keep a value intact while your script passes it around.

Understanding the Concept

When Bash expands an unquoted variable, it runs two extra steps on the result:

  1. Word splitting cuts the value into several words wherever it finds a character from IFS (by default space, tab and newline).
  2. Filename expansion (globbing) treats each word that contains *, ? or [ as a pattern and replaces it with the matching file names.

Double quotes turn both steps off. The folder used below contains the files a.txt, b.txt and notes.md:

input='my report *.txt'
printf '[%s]\n' $input
printf '[%s]\n' "$input"
[my]
[report]
[a.txt]
[b.txt]
[my report *.txt]

Unquoted, the single value became four arguments: two words, and a pattern that matched two files. Quoted, printf received exactly one argument containing exactly what the user typed.

An empty value is a second trap. Unquoted, an empty variable disappears completely, so the command receives one argument fewer:

name=''
[ -n $name ] && echo "test says: not empty (wrong)"
[ -n "$name" ] || echo "test says: empty (right)"
test says: not empty (wrong)
test says: empty (right)

Without quotes, the first test became [ -n ]. With a single argument, [ only checks that this argument (-n) is a non-empty string, which it is. The quoted version passes an empty string and gives the correct answer.

The basic rule follows from these two examples: put double quotes around every expansion of user data: "$var", "${array[@]}", "$@", "$(command)".

Places Where Quoting Changes the Meaning

Double quotes around arguments are only the start. Several Bash constructs treat an unquoted value as a pattern or a regular expression, even inside [[ ]] where word splitting does not happen. In these places, quoting decides whether the user's text is matched literally or interpreted.

The Right Side of == and != in [[ ]]

answer='*'
[[ yes == $answer ]] && echo "unquoted rhs: yes matches pattern *"
[[ yes == "$answer" ]] || echo "quoted rhs: yes is not the literal *"
unquoted rhs: yes matches pattern *
quoted rhs: yes is not the literal *

Unquoted, the user's * became a pattern that matches anything, so a check such as [[ $input == $expected ]] could be passed by typing *. Quoted, the comparison is an exact string comparison.

The Right Side of =~

re='a.c'
[[ abc =~ $re ]] && echo "unquoted: abc matches regex a.c"
[[ abc =~ "$re" ]] || echo "quoted: abc does not contain literal a.c"
[[ 'xa.cx' =~ "$re" ]] && echo "quoted: xa.cx contains literal a.c"
unquoted: abc matches regex a.c
quoted: abc does not contain literal a.c
quoted: xa.cx contains literal a.c

With =~, an unquoted variable is a regular expression, so the dot matches any character. A quoted variable is matched as literal text. Keep the regular expression in a variable you wrote yourself, and quote any user text that must be found literally.

case Patterns

choice='*'
case yes in $choice) echo "case unquoted: matched yes";; esac
case yes in "$choice") echo "matched";; *) echo "case quoted: no match";; esac
case unquoted: matched yes
case quoted: no match

The same rule applies: an unquoted expansion in a case pattern is a pattern; a quoted one is literal text.

Pattern Removal and Replacement

Parameter expansions such as ${var#pattern}, ${var%pattern} and ${var//pattern/replacement} (lessons 54 and 152) also treat an unquoted inner variable as a pattern:

file='report[1].txt'
pre='report[1]'
echo "${file#$pre}"
echo "${file#"$pre"}"
report[1].txt
.txt

Unquoted, report[1] is a pattern meaning "report followed by the character 1", which does not match the start of report[1].txt, so nothing was removed. Quoted, the brackets are literal and the prefix is removed.

The replacement part needs quotes too. Since Bash 5.2, the option patsub_replacement is on by default, and an unquoted & in the replacement stands for the matched text:

line='price: 10$ (approx)'
old='10$' new='&20'
echo "${line//"$old"/$new}"
echo "${line//"$old"/"$new"}"
price: 10$20 (approx)
price: &20 (approx)

When both the search text and the replacement come from the user, quote both: ${line//"$old"/"$new"}.

Reading Input Without Changing It

Quoting protects a value after it is stored. It cannot repair a value that read has already changed while reading. By default, read removes backslashes and trims leading and trailing spaces:

printf '%s\n' 'C:\temp\new  ' | { read v; printf '[%s]\n' "$v"; }
printf '%s\n' 'C:\temp\new  ' | { read -r v; printf '[%s]\n' "$v"; }
printf '%s\n' '  C:\temp\new  ' | { IFS= read -r v; printf '[%s]\n' "$v"; }
[C:tempnew]
[C:\temp\new]
[  C:\temp\new  ]
  • read v treated each backslash as an escape character and dropped it, and trimmed the trailing spaces.
  • read -r keeps backslashes.
  • IFS= read -r also keeps leading and trailing whitespace.

Use IFS= read -r whenever you read user text. If you want trimmed input, trim it yourself later, so the decision is visible in the code.

Passing Values That Look Like Options

A value that starts with - is read as an option by most commands. Quoting does not help here, because the quoted value is still a separate argument that begins with a dash. In the following example, words.txt contains the lines alpha, beta and x-vy, and the standard input of grep comes from a pipe that sends the line gamma:

q='-v'
printf 'gamma\n' | grep "$q" words.txt
grep -e "$q" -- words.txt
gamma
x-vy

In the first command, grep read -v as the "invert match" option, then took words.txt as the pattern and searched standard input instead of the file. It printed gamma because that line does not contain the text words.txt. In a script without a pipe, the same command waits for keyboard input and seems to hang. In the second command, -e marks the user's value as the pattern, and -- ends option parsing before the file names.

echo has the same problem and cannot be fixed with --:

msg='-n'
echo "$msg"; echo "(end)"
printf '%s\n' "$msg"
msg2='a\tb'
echo -e "$msg2"
printf '%s\n' "$msg2"
(end)
-n
a	b
a\tb

echo took -n as its "no newline" option and printed nothing. With -e, it turned the user's \t into a tab. printf '%s\n' prints any value exactly. Use printf '%s\n' "$value" to print user data, and never use user data as the format argument of printf (lesson 155).

Showing Values Unambiguously

When a script prints a value in an error message or a log, invisible characters such as trailing spaces, tabs and newlines can hide what the value really was. Bash has two ways to print a value in a form that can be pasted back into Bash and gives exactly the same string: printf '%q' and the @Q operator.

v=$'it\'s a "test" $(id) \n done'
printf '%q\n' "$v"
echo "${v@Q}"
$'it\'s a "test" $(id) \n done'
$'it\'s a "test" $(id) \n done'

The newline is visible as \n, the single quote is escaped, and $(id) is shown as text, not run. For values without control characters, @Q uses plain single quotes, as in ' Ravi ', which makes leading and trailing spaces obvious. Use these forms in error messages such as invalid topic: ${topic@Q}.

Passing Several Values: "$@" and Arrays

The positional parameters are user input too. Only "$@" passes them on exactly as they were received:

show() { printf '<%s>' "$@"; echo; }
f() { show $@; show "$*"; show "$@"; }
f 'one two' 'three'
<one><two><three>
<one two three>
<one two><three>
  • $@ unquoted splits one two into two words (and would also expand patterns).
  • "$*" joins all arguments into one string.
  • "$@" keeps each argument as it was: two arguments, the first containing a space.

When a script builds a command from several user values, store the command in an array and run it with "${cmd[@]}" (lesson 97), not in a string. An array keeps each element as one argument; a string has to be split again and loses that information.

Quoting for Other Languages

Bash quoting only protects values from Bash. When a value is placed inside text that another language will parse, such as JSON, a URL, SQL, HTML or a configuration file, that language has its own special characters. Shell quotes cannot protect against them, and trying to escape them by hand is error-prone.

The safe approach is to let a tool that understands the target format insert the value. For JSON, jq takes values with --arg:

name='Ana "the admin"'; note=$'line1\nline2 \\ end'
jq -n --arg name "$name" --arg note "$note" '{name: $name, note: $note}'
printf '{"name": "%s"}\n' "$name" | jq .
{
  "name": "Ana \"the admin\"",
  "note": "line1\nline2 \\ end"
}
jq: parse error: Invalid literal at line 1, column 19

jq escaped the quotes, the newline and the backslash correctly. The JSON built with printf was broken by the quotes in the name. With a carefully chosen value, string-built JSON can also be made to contain extra fields.

The same idea applies to other formats:

TargetSafe tool
JSONjq --arg name "$value"
URL query textjq -rn --arg t "$value" '$t|@uri' or curl --data-urlencode
SQLthe database client's parameter feature, never string building
awkENVIRON or -v (lesson 155)
remote shell (ssh)printf '%q' (lesson 155)

For example, jq URL-encodes a search term in one line:

term='C++ & Rust/50%'
jq -rn --arg t "$term" '$t|@uri'
C%2B%2B%20%26%20Rust%2F50%25

Here Documents

In an unquoted here document, variables are expanded, but the result of an expansion is not parsed again. So user data in a here document is not run as code:

user='$(id -un)'
cat <<END
Hello $user
END
cat <<'END'
Literal $user
END
Hello $(id -un)
Literal $user

The first document printed the user's text $(id -un) without running it. The danger comes later: if the generated text is a script, a configuration file or a command that something else will run, the user's text becomes code at that point. Treat generated files the same way as bash -c strings, and quote values for the target format before writing them.

Validating Before Using

Quoting keeps a value intact. It does not make the value acceptable. A correctly quoted file name can still be ../../etc/passwd, and a correctly quoted number can still be abc. Validation is a separate step that comes before use:

  • check that required values are not empty;
  • limit length where it matters;
  • use an allowlist pattern for values that become labels, identifiers or parts of file names, for example [[ $topic =~ ^[a-z0-9-]{1,20}$ ]];
  • reject the value with a clear message that shows it with @Q.

Allowlists say what is allowed. That is safer than trying to list every dangerous character, which is easy to get wrong. Lesson 161 covers validation of paths and file names in detail.

A Complete Example: A Feedback Collector

feedback.sh stores short feedback messages from users in a JSON Lines file (one JSON object per line) and searches them. Names and messages may contain any characters, the topic must be a short label, and nothing the user types may change what the script does.

#!/usr/bin/env bash
# feedback.sh: store feedback from a user safely as JSON lines
# usage: feedback.sh add  (reads NAME, TOPIC and MESSAGE from standard input)
#        feedback.sh find TEXT
set -uo pipefail

store=${FEEDBACK_FILE:-feedback.jsonl}
log=${FEEDBACK_LOG:-feedback.log}

die() { printf '%s: %s\n' "${0##*/}" "$1" >&2; exit 2; }

add() {
  local name topic message
  IFS= read -r -p 'Name: ' name || die 'no name given'
  IFS= read -r -p 'Topic: ' topic || die 'no topic given'
  IFS= read -r -p 'Message: ' message || die 'no message given'

  [[ -n ${name//[[:space:]]/} ]] || die 'name must not be empty'
  (( ${#message} <= 500 )) || die 'message is longer than 500 characters'
  # Topic is used as a label: allow only a small, known set of characters
  [[ $topic =~ ^[a-z0-9-]{1,20}$ ]] || die "invalid topic: ${topic@Q} (use a-z, 0-9 and -)"

  # jq builds the JSON; the values arrive as data with --arg
  jq -cn --arg name "$name" --arg topic "$topic" --arg message "$message" \
     --arg time "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
     '{time: $time, name: $name, topic: $topic, message: $message}' >> "$store" ||
    die 'could not write the feedback file'

  # The log line shows every value quoted, so hidden characters are visible
  printf '%s added name=%s topic=%s\n' "$(date -u +%FT%TZ)" "${name@Q}" "${topic@Q}" >> "$log"
  printf 'Saved feedback from %s about %s.\n' "$name" "$topic"
}

find_text() {
  local text=$1
  [[ -n $text ]] || die 'search text must not be empty'
  # jq compares the text literally: no regex, no shell, no options
  jq -r --arg t "$text" \
     'select((.message | contains($t)) or (.name | contains($t)))
      | "\(.time)  \(.name) [\(.topic)]: \(.message)"' -- "$store"
}

case ${1-} in
  add)  add ;;
  find) (( $# == 2 )) || die 'usage: feedback.sh find TEXT'; find_text "$2" ;;
  *)    die 'usage: feedback.sh add | find TEXT' ;;
esac

How It Works

  • Reading. Each answer is read with IFS= read -r, so backslashes, leading spaces and trailing spaces are kept exactly. -p shows the prompt only when standard input is a terminal, so the prompts do not appear when input is piped, as in the runs below. If input ends early, read fails and the script stops with a message.
  • Validation. The name must contain at least one non-space character: ${name//[[:space:]]/} removes all whitespace, and the test checks that something remains. The message is limited to 500 characters. The topic, which acts as a label, must match an allowlist pattern. The pattern is written directly after =~ without quotes, so it is a regular expression; the user's value is on the left side, where it is plain data.
  • Storing. jq -cn creates a compact JSON object from nothing (-n). All four values arrive with --arg, so jq escapes quotes, backslashes and newlines correctly, and no value can add fields or break the line. The jq program itself is in single quotes and contains no shell variables.
  • Logging. The log line uses ${name@Q} and ${topic@Q}, so leading spaces and quotes are visible to whoever reads the log.
  • Searching. The search text goes to jq with --arg and is compared with contains, which matches literal text. -- before the file name stops jq from reading an unusual file name as an option.
  • Dispatching. case ${1-} in uses ${1-} so the script works under set -u when no argument is given. Every "$2" and "$text" is quoted.

Running the Complete Example

The inputs are piped in, one line per answer:

printf '%s\n' 'Ana "the admin" O'"'"'Neil' 'billing' 'Charged twice; please check $(invoice) & refund \o/' | ./feedback.sh add
printf '%s\n' '  Ravi  ' 'ui' 'Dark mode -n option is *great*' | ./feedback.sh add
printf '%s\n' 'Eve' 'x; rm -rf ~' 'hi' | ./feedback.sh add; echo "status $?"
printf '%s\n' '   ' 'ui' 'hi' | ./feedback.sh add; echo "status $?"
printf '%s\n' 'Eve' | ./feedback.sh add; echo "status $?"
Saved feedback from Ana "the admin" O'Neil about billing.
Saved feedback from   Ravi   about ui.
feedback.sh: invalid topic: 'x; rm -rf ~' (use a-z, 0-9 and -)
status 2
feedback.sh: name must not be empty
status 2
feedback.sh: no topic given
status 2

The first two entries were stored, including quotes, $( ), &, a backslash, -n and *. The topic x; rm -rf ~ was refused by the allowlist and shown quoted in the error message; it was never run. A name made only of spaces and an input that ended after the name were also refused.

The stored file and the log show the values exactly:

cat feedback.jsonl
cat feedback.log
{"time":"2026-11-24T08:56:09Z","name":"Ana \"the admin\" O'Neil","topic":"billing","message":"Charged twice; please check $(invoice) & refund \\o/"}
{"time":"2026-11-24T08:56:09Z","name":"  Ravi  ","topic":"ui","message":"Dark mode -n option is *great*"}
2026-11-24T08:56:09Z added name='Ana "the admin" O'\''Neil' topic='billing'
2026-11-24T08:56:09Z added name='  Ravi  ' topic='ui'

Searching treats the text literally:

./feedback.sh find '$(invoice)'
./feedback.sh find '-n'
./feedback.sh find '*'
./feedback.sh find '.*'; echo "status $?"
./feedback.sh find; echo "status $?"
2026-11-24T08:56:09Z  Ana "the admin" O'Neil [billing]: Charged twice; please check $(invoice) & refund \o/
2026-11-24T08:56:09Z    Ravi   [ui]: Dark mode -n option is *great*
2026-11-24T08:56:09Z    Ravi   [ui]: Dark mode -n option is *great*
status 0
feedback.sh: usage: feedback.sh find TEXT
status 2

$(invoice) was found as text, -n was a search term rather than an option, and * matched only the message that contains an asterisk. .* matched nothing, because no message contains a dot followed by a star; jq still exits with status 0 when no line matches, so a caller that needs a "not found" status would check whether the output is empty.

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 Quoting User Input Safely and get answers drawn from it.

Signed-in readers only.