0
0
Bash Scriptingscripting~5 mins

Escape characters (\) in Bash Scripting

Choose your learning style9 modes available
Introduction
Escape characters let you use special symbols or spaces in commands without confusion.
When you want to include spaces in file or folder names in commands.
When you need to use special characters like $, *, or & literally in a command.
When writing scripts that include quotes inside quotes.
When you want to prevent the shell from interpreting a character as a command.
When you want to write multi-line commands by escaping the newline.
Syntax
Bash Scripting
backslash \ followed by the character to escape
The backslash \ tells the shell to treat the next character as normal text.
Use it before spaces, quotes, or special symbols to avoid errors.
Examples
Use \ before space to change directory to a folder named 'My Documents'.
Bash Scripting
cd My\ Documents
Prints 'Hello World!' with spaces and exclamation mark escaped.
Bash Scripting
echo Hello\ World\!
Prints: She said "Hello" using escaped double quotes inside double quotes.
Bash Scripting
echo "She said \"Hello\""
Uses \ to escape newline for multi-line commands (note: in bash, \n is literal unless interpreted).
Bash Scripting
echo Line1\
Line2
Sample Program
This script shows how to use backslash to escape spaces in folder names, special characters like $ and *, and quotes inside quotes.
Bash Scripting
#!/bin/bash

# Create a folder with space in name
mkdir My\ Folder

# List the folder
ls My\ Folder

# Print a message with special characters
echo "This is a dollar sign: \$ and a star: *"

# Print a quote inside quotes
echo "He said \"Bash is fun!\""
OutputSuccess
Important Notes
Not all characters need escaping; only those with special meaning in bash.
You can also use single quotes to avoid escaping most characters.
Escaping helps avoid errors when file names or commands have spaces or symbols.
Summary
Escape character \ lets you use special symbols or spaces safely in bash commands.
Use \ before spaces, quotes, or special symbols to treat them as normal text.
Escaping helps your scripts run without errors caused by special characters.