Quoting User Input Safely
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:
- Word splitting cuts the value into several words wherever it finds a character from
IFS(by default space, tab and newline). - 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 vtreated each backslash as an escape character and dropped it, and trimmed the trailing spaces.read -rkeeps backslashes.IFS= read -ralso 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 splitsone twointo 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:
| Target | Safe tool |
|---|---|
| JSON | jq --arg name "$value" |
| URL query text | jq -rn --arg t "$value" '$t|@uri' or curl --data-urlencode |
| SQL | the database client's parameter feature, never string building |
| awk | ENVIRON 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.-pshows 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,readfails 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 -cncreates a compact JSON object from nothing (-n). All four values arrive with--arg, sojqescapes quotes, backslashes and newlines correctly, and no value can add fields or break the line. Thejqprogram 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
jqwith--argand is compared withcontains, which matches literal text.--before the file name stopsjqfrom reading an unusual file name as an option. - Dispatching.
case ${1-} inuses${1-}so the script works underset -uwhen 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.