Escaping Special Characters

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

Some characters mean something to Bash before they ever reach a command: a space separates words, $ starts an expansion, * is a wildcard, ; ends a command, and & starts a background job. Escaping removes that special meaning from a single character so Bash treats it as ordinary text. The main tool is the backslash (0), and Bash also offers $'...', printfand--` for situations where a backslash alone is not enough.

The Backslash Outside Quotes

A backslash placed in front of a character tells Bash to take that one character literally. Outside quotes, it works on any character.

echo Price: \$5
echo a\ b
echo \*
echo \"quoted\"

Output:

Price: $5
a b
*
"quoted"
  • \$5 printed a dollar sign instead of starting a variable expansion.
  • a\ b kept the space inside one word.
  • 0 printed an asterisk instead of expanding to file names.
  • \"quoted\" printed the double quotes instead of starting a quoted string.

The backslash itself is removed. Bash uses it as an instruction and does not pass it on to the command. You can confirm that a backslash-escaped space really produces one argument:

printf '[%s]\n' a\ b

Output:

[a b]

Characters That Need Escaping

These characters have a special meaning to Bash when they appear unquoted. Escape any of them when you want the literal character.

CharacterSpecial meaningEscaped form
space, tabseparates words\
$variable, command or arithmetic expansion\$
* ? [ ]wildcard patterns0 \? 1 2
;ends a command\;
&runs a command in the background\&
|pipe|
< >redirection0 1
( )subshells and grouping0 1
{ }brace expansion0 1
~home directory (at the start of a word)0
#starts a comment (at the start of a word)0
" 'start a quoted string\" \'
``the escape character itself0

Some of them only matter in certain positions. A # starts a comment only at the beginning of a word, and a ~ is expanded only at the start of a word:

echo \#not-a-comment
echo not#comment
echo \~
echo \{a,b\}

Output:

#not-a-comment
not#comment
~
{a,b}

The second command needed no backslash because the # was in the middle of a word. The escaped 0a,b1 stopped Bash from treating the braces as a brace expansion.

Escaping characters that have no special meaning does nothing harmful. Bash simply drops the backslash:

echo \a\b\c

Output:

abc

Escaping the Shell Operators

Operators such as &, ; and % are easy to type by accident in text. Escaping each one turns it back into plain text:

echo hello \& goodbye
echo semi\; colon
echo 100\% sure

Output:

hello & goodbye
semi; colon
100% sure

Without the backslash, echo hello & goodbye would run echo hello in the background and then try to run a command named goodbye. The % in the last example never needed escaping, because it has no special meaning in the middle of an ordinary word. The line shows that an unnecessary backslash is harmless.

Escaping Spaces in File Names

A file name with a space looks like two arguments to Bash unless the space is protected. A backslash is one way to do it, and quotes are the other.

touch "my file.txt"
ls my\ file.txt

Output:

my file.txt

Tab completion in a terminal inserts these backslashes for you. In scripts, quoting a whole name ("my file.txt") is usually easier to read than escaping each space.

Escaping the Newline: Line Continuation

A backslash at the very end of a line removes the newline that follows it, so one command can span several lines:

echo one \
  two \
  three

Output:

one two three

Bash joined the three lines into one command. The extra spaces at the start of the continuation lines were ordinary separators between words, so echo printed a single space between them. There must be nothing after the backslash, not even a trailing space, or the backslash will escape that space instead of the newline.

Line continuation is used for long commands with many options, and it also works between quoted pieces:

echo "A"\
"B"

Output:

AB

Backslashes Inside Quotes

Quotes change how backslashes behave. Inside single quotes, a backslash is just a character, and nothing can be escaped. Inside double quotes, a backslash only works in front of $, a backtick, ", `` and a newline.

x=5
echo "cost: \$$x"
echo "path: C:\\Users"
echo "tab: \t"
echo "quote: \"hi\""

Output:

cost: $5
path: C:\Users
tab: \t
quote: "hi"

In \$$x, the first dollar sign is escaped and printed, and the second one starts the expansion of x. The sequence \t is not on the list of escapable characters, so both characters stayed. Lesson 46 describes these rules in the context of quoting.

Producing Tabs and Newlines

A backslash in front of a letter, such as \t, does not create a tab in Bash itself. The escape sequences for tabs and newlines belong to certain commands and to a special quote form. There are three common ways to get them.

echo -e asks echo to interpret backslash sequences in its arguments:

echo -e "a\tb\nc"
echo 'a\tb'
echo -e 'a\tb'

Output:

a	b
c
a\tb
a	b

Plain echo printed a\tb literally. Adding -e made echo convert \t to a tab. The option behaves differently in some shells, so printf is more dependable.

printf always interprets escape sequences in its format string:

printf 'a\tb\nc\n'
printf '%s\n' 'a\tb'
printf '%b\n' 'a\tb'

Output:

a	b
c
a\tb
a	b

The first command used the escapes in the format, so they were converted. The second passed a\tb as data to %s, which prints data unchanged. The third used %b, which asks printf to interpret escapes in the data.

ANSI-C quoting with $'...' makes Bash itself convert the escapes before any command runs:

echo $'a\tb'
echo $'line1\nline2'
echo $'single \' quote'

Output:

a	b
line1
line2
single ' quote

Inside $'...', the sequences \t (tab), \n (newline), 0 (backslash), \' (single quote) and \xHH (a character by hexadecimal code) are recognized. For example, $'\x41' produces the letter A. This is the only quote form in which a single quote can be escaped with a backslash.

File Names That Start with a Dash

A name that starts with - looks like an option to most commands. Escaping with a backslash does not help here, because the command still receives a leading dash. The solutions work on the command, not on Bash:

touch ./-n
ls -- -n
ls ./-n

Output:

-n
./-n
  • -- is a convention that means "no more options follow." Everything after it is treated as a file name.
  • ./-n puts a path in front of the name, so it no longer begins with a dash.

Letting printf Do the Escaping: %q

When a value contains many special characters, printf '%q' prints it in a form that Bash can read back safely, with backslashes added where needed:

v='it'"'"'s a "test" $HOME'
printf '%q\n' "$v"

Output:

it\'s\ a\ \"test\"\ \$HOME

Every character that would be special to Bash received a backslash. This is useful when a script has to generate a command line, a configuration line or a log entry that will be read by a shell again.

Escaping for the Command, Not for Bash

Two different programs may need to understand an escape. Bash removes one layer of quoting, and the command may then apply its own meaning. A common case is a regular expression, where . matches any character:

printf 'a.b\naxb\n' > r.txt
grep a.b r.txt
grep 'a\.b' r.txt

Output:

a.b
axb
a.b

The first grep treated the dot as "any character" and matched both lines. In the second command, the single quotes delivered the text a0b to grep untouched, and grep read 1 as a literal dot. If you wrote a2b without quotes, Bash would remove the backslash first, and grep would receive a.b.

The same idea applies to find -exec. The semicolon that ends the command belongs to find, so Bash must not consume it:

touch a1.log a2.log
find . -name '*.log' -exec echo found {} \; | sort

Output:

found ./a1.log
found ./a2.log

The quotes around '*.log' stopped Bash from expanding the pattern, so find matched file names itself. The \; passed a literal semicolon to find as the terminator for -exec.

Escaping Wildcards

An escaped wildcard is matched literally, just like a quoted one:

echo *.log
echo \*.log
echo "*.log"

Output:

a1.log a2.log
*.log
*.log

The unquoted pattern expanded to the two files created above. The escaped and quoted forms printed the pattern text.

Here Documents: Escaping a Whole Block

A here document feeds several lines to a command. Quoting the delimiter turns off expansion for the whole block, which is like putting single quotes around all of it:

cat <<'EOT'
Literal $HOME and \n here
EOT
cat <<EOT
Expanded $((1+1)) and \$HOME
EOT

Output:

Literal $HOME and \n here
Expanded 2 and $HOME

With the delimiter quoted ('EOT'), nothing was expanded. With an unquoted delimiter, Bash expanded $((1+1)) but still honored the backslash in \$HOME. Here documents have their own lesson later in the series.

Choosing an Escaping Method

  • For one special character inside an unquoted word, use a backslash.
  • For several special characters in a row, or a whole value, use quotes.
  • For tabs, newlines or characters by code, use $'...' or printf.
  • For names that start with a dash, use -- or a ./ prefix.
  • When a command applies its own escaping rules, quote the argument so the command receives the backslashes you wrote.

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 Escaping Special Characters and get answers drawn from it.

Signed-in readers only.