Single Quotes vs. Double Quotes

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 46 of 205

Bash gives you two everyday ways to wrap text in quotation marks, and they behave very differently. Single quotes ('...') keep every character exactly as you typed it. Double quotes ("...") keep most characters literally but still let Bash substitute variables, command output and arithmetic results. Knowing which quote to reach for decides whether a command receives the text you intended or something Bash rewrote on the way.

Why Quoting Exists

Before Bash runs a command, it reads the line and processes it in stages. It splits the line into words at spaces, then replaces variables, runs command substitutions, expands wildcards such as *, and finally hands the resulting words to the program. Several characters have a special meaning during that process: the space, $, *, ?, ;, &, |, <, >, (, ), # and the quote characters themselves.

Quoting is how you tell Bash, "treat this text as plain data, not as syntax." The two quote styles differ in how much of that processing they switch off.

FeatureUnquotedDouble quotesSingle quotes
Variable expansion ($name)YesYesNo
Command substitution ($(cmd))YesYesNo
Arithmetic expansion ($((1+2)))YesYesNo
Splitting into words at spacesYesNoNo
Wildcard expansion (*.txt)YesNoNo
Tilde expansion (~)YesNoNo
Backslash escapesYesOnly before a few charactersNo

Single Quotes: Everything Is Literal

Inside single quotes, Bash does no interpretation at all. Every character stands for itself, including $, backticks and backslashes. The only character that has meaning is the closing single quote.

name="Ana"
echo 'Hello, $name'
echo "Hello, $name"

Output:

Hello, $name
Hello, Ana

The first command prints the characters $name because the single quotes stopped Bash from looking at the dollar sign. The second command lets Bash replace $name with its value, Ana.

Single quotes are the right choice whenever you want text to arrive untouched: regular expressions, awk programs, sed scripts, and strings that contain many $ or `` characters.

echo 'Price: $5, path: C:\Users, glob: *.txt'

Output:

Price: $5, path: C:\Users, glob: *.txt

None of those special characters did anything, because nothing inside single quotes is interpreted.

Double Quotes: Literal Except for a Few Characters

Double quotes protect spaces and wildcards, but Bash still performs the substitutions that begin with $ or a backtick. Three kinds of expansion keep working inside double quotes:

echo "Home: $HOME"
echo "Sum: $((2 + 3))"
echo "Today is $(echo Friday)"

Output (the home directory depends on your account):

Home: /root
Sum: 5
Today is Friday
  • $HOME is a variable expansion. Bash replaces it with the value of the variable.
  • $((2 + 3)) is arithmetic expansion. Bash calculates the result and inserts it.
  • $(echo Friday) is command substitution. Bash runs the command and inserts its output.

Later lessons cover the last two in depth. For now, the important point is that double quotes leave them switched on.

Escaping Inside Double Quotes

A backslash inside double quotes only has special meaning in front of five characters: $, a backtick, ", ``, and a newline. In front of anything else, the backslash stays as an ordinary character.

echo "Price: \$5 and a backslash \\ and a quote \" and backtick \` "
echo "Not special: \n \t \a"

Output:

Price: $5 and a backslash \ and a quote " and backtick ` 
Not special: \n \t \a

The first line uses the backslash to print a literal dollar sign, backslash, double quote and backtick. In the second line, \n, \t and \a are not on the list, so Bash passes both characters through unchanged. This also means that echo "a\tb" does not print a tab. Lesson 47 shows the tools that do.

The Apostrophe Problem

Because a single quote ends a single-quoted string, you cannot put an apostrophe inside single quotes, not even with a backslash. There are two common ways around it.

The simplest is to use double quotes for text that contains an apostrophe:

echo "It's fine"

Output:

It's fine

When the text must stay inside single quotes, close the quote, add an escaped apostrophe, and reopen the quote:

echo 'It'\''s fine'

Output:

It's fine

Read 'It'\''s fine' as three pieces joined together with no spaces between them: 'It', then \' (an escaped, literal apostrophe), then 's fine'. Bash glues adjacent pieces into one word.

Quotes and Word Splitting

After expanding a variable, Bash splits the unquoted result into separate words wherever it finds spaces, tabs or newlines. This is called word splitting. Double quotes switch it off, so the whole value stays in one piece.

file="my notes.txt"
printf '[%s]\n' $file
printf '[%s]\n' "$file"

Output:

[my]
[notes.txt]
[my notes.txt]

printf '[%s]\n' prints each argument it receives inside square brackets, which makes the argument boundaries visible. The unquoted $file was split into two arguments, my and notes.txt. The quoted "$file" stayed as one argument. If a command like rm $file ran with the unquoted form, it would try to remove two files named my and notes.txt instead of one file named my notes.txt.

Quoting also preserves runs of spaces in literal text:

echo Hello      World
echo "Hello      World"

Output:

Hello World
Hello      World

Without quotes, Bash sees two words and echo prints them separated by a single space. With quotes, Bash sees one word that contains the extra spaces, and echo prints it as is.

An empty variable shows the same effect:

empty=""
printf '[%s]\n' $empty "$empty"

Output:

[]

The unquoted $empty vanished and produced no argument at all. The quoted "$empty" produced one empty argument. Only one line was printed because printf received only one argument.

Quotes and Wildcards

Wildcard characters are expanded only when they are unquoted. Both kinds of quotes switch globbing off.

mkdir -p g && cd g && touch a.txt b.txt && cd ..
echo g/*.txt
echo "g/*.txt"
echo 'g/*.txt'

Output:

g/a.txt g/b.txt
g/*.txt
g/*.txt

The unquoted pattern was replaced by the names of the matching files. The two quoted versions were printed literally. The same rule applies to ~: unquoted ~ becomes your home directory, while "~" and '~' stay as a tilde character.

Mixing Quote Styles in One Word

Quoted and unquoted pieces that touch each other form a single word, so you can switch styles in the middle of an argument. This lets you keep most of a string literal while still expanding one variable:

name="Ana"
echo 'single '"double $name"' single $name'

Output:

single double Ana single $name

The word has three parts:

  1. 'single ' is literal text.
  2. "double $name" is expanded, so $name becomes Ana.
  3. ' single $name' is literal again, so $name stays as typed.

A common practical version is building a command string where most of it must stay literal but one value must be inserted:

dir="/var/log"
echo 'Searching in '"$dir"' for $HOME-style names'

Output:

Searching in /var/log for $HOME-style names

Protecting a Variable Name from Following Text

When a variable is followed by letters, digits or underscores, Bash reads them as part of the variable name. Braces mark exactly where the name ends:

fruit=apple
echo "${fruit}s and $fruits."

Output:

apples and .

${fruit}s expanded the variable named fruit and then added the letter s. $fruits was read as a different variable named fruits, which does not exist, so it expanded to nothing.

Strings That Span Several Lines

Both quote styles allow a string to continue across lines. The newline becomes part of the string:

echo "line1
line2"
echo 'a
b'

Output:

line1
line2
a
b

If you end a line with a backslash inside double quotes, Bash removes both the backslash and the newline, joining the lines:

echo "abc\
def"

Output:

abcdef

Inside single quotes the backslash would stay in the text, because nothing is interpreted there.

ANSI-C Quoting with $'...'

Bash has a third quote form, $'...', which understands escape sequences such as \t for a tab and \n for a newline. It is covered in the next lesson, but a first look shows how it differs from the two quote styles above:

printf '%s\n' $'tab:\there' $'newline:\nnext' $'it\'s'

Output:

tab:	here
newline:
next
it's

Inside $'...', a backslash is an escape character, and \' is allowed to produce a literal apostrophe.

Passing Code to Another Shell

A frequent use of single quotes is giving a command string to another program that will interpret it later. With bash -c, single quotes keep the inner shell's variables from being expanded by the outer shell:

bash -c 'echo "inner: $0"' demo
x=outer
bash -c "echo outer-expanded: $x"

Output:

inner: demo
outer-expanded: outer

In the first command, the single quotes delivered the text echo "inner: $0" intact, and the child shell expanded $0 itself. The word demo after the command string becomes $0 inside the child shell. In the second command, the double quotes let the outer shell expand $x first, so the child shell received echo outer-expanded: outer and had no variable left to expand.

The same distinction matters for ssh host '...', sudo sh -c '...', find -exec sh -c '...' and similar commands.

Quoting Arrays

An array expanded with @ inside double quotes produces one word per element, even when elements contain spaces. Without quotes, each element is split further:

arr=("a b" "c d")
printf '[%s]\n' ${arr[@]}
printf '[%s]\n' "${arr[@]}"

Output:

[a]
[b]
[c]
[d]
[a b]
[c d]

The unquoted form turned two elements into four words. The quoted form kept the two original elements. Arrays get their own lessons later in the series.

Choosing Between the Two

The decision usually follows one question: should Bash look inside this text?

  • Use single quotes when the text must stay exactly as written. Patterns for grep, sed and awk, strings full of $ and ``, and code handed to another shell all fit here.
  • Use double quotes when the text contains variables, command substitutions or arithmetic that Bash should expand, or when a value may contain spaces and must stay one word.
  • Use no quotes only when you want word splitting and wildcard expansion, such as ls *.txt or for n in 1 2 3.
  • Combine the styles in one word when a mostly literal string needs one expanded value.
grep '^Error: ' app.log
grep "^Error: $code" app.log

The first command passes the pattern literally. The second inserts the value of $code into the pattern before grep sees it.

In an interactive terminal, double quotes have one more catch: the exclamation mark can trigger history expansion, so a line such as echo "Hello!" may behave unexpectedly. Single quotes avoid this, and scripts are not affected because history expansion is turned off for them.

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 Single Quotes vs. Double Quotes and get answers drawn from it.

Signed-in readers only.