Why Quoting Variables Matters

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 55 of 205

Putting double quotes around a variable expansion, as in "$name", is the single most important habit in Bash scripting. Without the quotes, Bash splits the value into several words and then treats any wildcard characters in those words as patterns. With the quotes, the value reaches the command exactly as it is stored, spaces and all.

Understanding the Rule

The rule fits in one sentence: an unquoted expansion is split into words and then used as a filename pattern, and a quoted one is not. The two lessons before this one explain the mechanisms, word splitting and filename expansion. This lesson shows what they do to real commands when a variable is left unquoted.

To make the examples visible, they use a folder with a few files whose names are typical of real life:

mkdir photos && cd photos
printf 'hello\n' > "my file.txt"
printf 'plain\n' > notes.txt
printf 'x\n' > "two  spaces.txt"
mkdir "my folder"
printf 'inside\n' > "my folder/inside.txt"

Two helper functions show what a command receives:

count() { echo "$# arguments"; }
show() { printf '[%s]\n' "$@"; }

What Happens to an Unquoted Expansion

When Bash meets $var outside quotes, it works in three steps:

  1. It replaces $var with its value.
  2. It splits the value into words at spaces, tabs and newlines (word splitting).
  3. It treats each word that contains *, ? or [ as a pattern and replaces it with matching file names (filename expansion).

With "$var" none of the last two steps happen. Everything in the following sections is a consequence of those steps.

Values With Spaces Become Several Arguments

The most common failure involves file and folder names that contain spaces:

f="my file.txt"
cat $f
cat "$f"

Output:

cat: my: No such file or directory
cat: file.txt: No such file or directory
hello

The unquoted $f became two words, my and file.txt, so cat looked for two files that do not exist. The quoted version passed one argument. The same thing happens with directories:

d="my folder"
ls $d
ls "$d"

Output:

ls: cannot access 'my': No such file or directory
ls: cannot access 'folder': No such file or directory
inside.txt

Counting arguments shows it directly:

count $f
count "$f"
count $d/inside.txt
count "$d"/inside.txt

Output:

2 arguments
1 arguments
2 arguments
1 arguments

The mistake is harmful when the command does more than read. Here mkdir creates the wrong things:

dir="new dir"
mkdir $dir
ls

Output (in a fresh, empty folder):

dir  new

Instead of one folder called new dir, Bash created two folders, new and dir. A later command such as mkdir "$dir/inner" then fails with mkdir: cannot create directory 'new dir/inner': No such file or directory. With commands that remove or overwrite files, the same mistake can touch files you never meant to name, which is why a later lesson on destructive commands insists on quoting.

Empty Values Disappear

An unquoted empty variable does not become an empty argument. It becomes no argument at all, which changes the shape of the command:

target=""
count $target
count "$target"

Output:

0 arguments
1 arguments

This breaks conditions written with the [ command:

empty=""
[ $empty = "yes" ]
echo "status: $?"
[ "$empty" = "yes" ]
echo "status: $?"

Output:

bash: [: =: unary operator expected
status: 2
status: 1

After the empty variable vanished, [ saw only = yes, which is not a valid test. With quotes, [ received an empty first argument and a normal comparison was made, which was simply false (status 1).

A related trap produces a wrong answer instead of an error:

empty=""
[ -n $empty ] && echo "true"
[ -n "$empty" ] && echo "true"

Output:

true

Only the first line printed. [ -n ] with the variable gone becomes a one-argument test, which is true for any non-empty text, here the string -n. The quoted form tests the actual (empty) value and is false.

Values with spaces break the same test in the other direction:

w="a b"
[ $w = "a b" ]
echo "status: $?"
[ "$w" = "a b" ]
echo "status: $?"

Output:

bash: [: too many arguments
status: 2
status: 0

And file tests are affected in the same way:

f="my file.txt"
[ -f $f ]
echo "status: $?"
[ -f "$f" ]
echo "status: $?"

Output:

bash: [: my: binary operator expected
status: 2
status: 0

Glob Characters in Values Are Expanded

A value that contains *, ? or [ is treated as a pattern when it is unquoted, even if you meant plain text:

note="Total: 5 * 3"
echo $note
echo "$note"

Output (in the photos folder):

Total: 5 my file.txt my folder notes.txt two  spaces.txt 3
Total: 5 * 3

The * matched every name in the folder. The effect is harmless with echo, but a program such as rm would treat the names as targets.

Patterns passed to commands that do their own matching are affected too:

pattern="*.txt"
find . -maxdepth 1 -name $pattern
find . -maxdepth 1 -name "$pattern"

Output (find does not sort its results, so the order of the three names may differ on your system):

find: paths must precede expression: `notes.txt'
find: possible unquoted pattern after predicate `-name'?
./my file.txt
./notes.txt
./two  spaces.txt

The unquoted $pattern was expanded by the shell into three file names, so find received -name "my file.txt" notes.txt "two spaces.txt" and rejected the extra words. The quoted form delivered the literal *.txt for find to use.

Whitespace and Newlines Are Lost

Splitting also discards the exact spacing of a value, because the words are rejoined with single spaces by echo:

text=$'line one\n   line two\twith tab'
echo $text
echo "$text"

Output:

line one line two with tab
line one
   line two	with tab

The quoted version preserved the newline, the leading spaces and the tab. This matters whenever you print, log or pass multi-line text.

Values That Start With a Dash

A value that begins with - can be mistaken for an option. Quotes do not solve this by themselves, because the shell removes them before the command runs, but they combine with the -- marker or a ./ prefix:

This example uses its own empty folder, so the odd file name does not affect the other examples:

mkdir dashdemo && cd dashdemo
touch -- "-v.txt"
name="-v.txt"
ls $name
ls -- "$name"
ls ./"$name"
cd ..

Output:

ls: invalid option -- '.'
Try 'ls --help' for more information.
-v.txt
./-v.txt

ls read -v.txt as a group of options. The first one, -v, is valid, but the . that follows is not, so it stopped with an error. The -- tells ls that options have ended, and ./ makes the name start with something other than a dash. The quotes in both working forms still protect against spaces.

Command Substitution and Loops

The output of $(...) is split like any other value. A loop over $(ls) breaks on names with spaces, because it loops over words instead of names:

for f in $(ls *.txt); do echo "piece: $f"; done

Output:

piece: my
piece: file.txt
piece: notes.txt
piece: two
piece: spaces.txt

Looping over a pattern is safe, because filename expansion produces one word per file:

for f in *.txt; do echo "item: $f"; done

Output:

item: my file.txt
item: notes.txt
item: two  spaces.txt

Reading a list of lines is also safer with while read than with for:

printf 'my file.txt\nnotes.txt\n' > list.txt
while IFS= read -r line; do echo "line: $line"; done < list.txt
for line in $(cat list.txt); do echo "word: $line"; done

Output:

line: my file.txt
line: notes.txt
word: my
word: file.txt
word: notes.txt

Arrays and Positional Parameters

Arrays follow the same rule, and the special form "${array[@]}" is how you pass every element as its own word:

files=("my file.txt" "notes.txt")
count ${files[@]}
count "${files[@]}"
count "${files[*]}"

Output:

3 arguments
2 arguments
1 arguments
  • Unquoted ${files[@]} was split again, so my file.txt became two words.
  • "${files[@]}" kept one word per element.
  • "${files[*]}" joined everything into a single word.

The script arguments $@ behave the same way:

args() { count $@; count "$@"; }
args "a b" "c d"

Output:

4 arguments
2 arguments

Quoting Inside Command Substitution

Quotes inside $(...) are independent of the quotes outside. Writing both pairs is correct and is the usual form:

f="my notes.txt"
printf 'hello\n' > "$f"
echo "$(basename "$f")"
echo "$(basename $f)"

Output:

my notes.txt
my

In the second command the inner $f was not quoted, so basename received two arguments, my and notes.txt. It treats a second argument as a suffix to remove, and it printed my. The outer quotes alone are not enough; each expansion needs its own.

Places Where Quotes Are Optional

Quotes are not required in contexts where Bash does no splitting or globbing:

a="x y"
b=$a
echo "$b"
case $a in "x y") echo "case ok";; esac
[[ $a == "x y" ]] && echo "[[ ok"

Output:

x y
case ok
[[ ok
  • A plain assignment such as b=$a stores the value without splitting.
  • The word after case is not split.
  • Inside [[ ... ]] the left side is not split.

Adding quotes in these places does no harm. The one place where quotes change the meaning inside [[ ]] is the right side of ==, which is treated as a pattern unless it is quoted:

pat="a*"
[[ "a b" == $pat ]] && echo "unquoted: pattern, match"
[[ "a b" == "$pat" ]] || echo "quoted: literal, no match"

Output:

unquoted: pattern, match
quoted: literal, no match

A Simple Rule in Practice

Quote every $ expansion, including "$var", "${var}", "$(command)", "$@" and "${array[@]}", and leave the quotes off only when you specifically want splitting or globbing. That choice is rare, and it should be visible in the code, for example with a comment. The static checker ShellCheck, covered in a later lesson, reports unquoted expansions with its warning SC2086, "Double quote to prevent globbing and word splitting". Scripts that also use set -u, described in a later lesson, catch variables that were never set, which complements quoting.

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 Quoting Variables Matters and get answers drawn from it.

Signed-in readers only.