FUNDAMENTALS A Complete Guide for Beginners
In Bash scripting, the concept of escaping characters hinders the intended functionality of special characters. Escaping in Bash ensures the preservation of the exact values of these characters. While working with special characters within strings, there might be occasions where it becomes necessary to escape them to maintain their literal significance. In this article, you will learn about special characters and some methods on how to escape string in bash.
What Are Special Characters in Bash?
In bash scripting, the characters with special meanings or purposes are called special characters. Bash accesses these characters with their non-literal values. Here are some of the special characters that may need to escape sometimes to preserve their literal values:
Special character | Description |
---|---|
Expansion ($) | Transforms a specific string or value into another form. Some kinds of expansion include variable expansion, command substitution, arithmetic expansion, etc. |
Single quotes (‘ ’) | Prevents word splitting, preserves the literal value, and prevents any kind of interpretation of the special characters. |
Double quotes (“ ”) | Prevents word splitting, and allows expansion and substitution. |
Exclamation (!) | Bash uses the character to reverse the output of a test expression. |
Wildcard (*,?) | Matches the filenames and patterns. |
Backquoted operator (`) | Bash uses it for command substitution. |
Newline character (\n) | Used for line breaks and formatting text. |
Backslash (\) | Prevents the interpretation of the following character as a special character. |
Tilde (~) | Represents the home directory in bash. For example, ls ~ indicates the current directory and ls ~/Documents shows the Documents directory. |
Why is It Important to Escape Characters in Bash?
Escaping is important to handle strings and variables and deal with various data in strings. For example, if you want to print these special characters “!”\t\s\f\s.##” using the echo command, then it will not show the expected result rather will return an error message. So, to keep the value of the special characters same as the input, it is necessary to escape these characters.
In bash scripting, single quotes preserve the literal value of each of the characters. It will not interpolate or expand the variable value or also not interpolate a command’s output. Now, let’s see an example of escaping multiple characters within single quotes:
#!/bin/bash
echo '!"\t\s\f\s.##'
#output !"\t\s\f\s.##
To escape special characters inside double quotes you have to use a backslash (\). Without a backslash, it won’t show the expected result. Take a look at the following code:
#!/bin/bash
echo "\"\\t\\s\\f\\s.##"
#output "\t\s\f\s.##
5 Methods to Escape Special Characters
To escape special characters in bash, backslash is widely used. In this section, including the backslash, you will get an overview of some other methods that will help you understand how to escape special characters. Here are the 5 methods to escape special characters:
1. Using Backslash
Backslash is a special character that is mainly used to escape special characters by making them literal. Bash uses this character to escape single quotes, double quotes, backslash themselves, and other special characters.
To escape special characters use non-quoted backslash immediately before the character you want to preserve the special character. Here are some of the syntaxes to escape special characters using backslash:
-
To escape the parentheses follow the code below:
echo "This is an example with "\(escaped_parentheses\) #output: This is an example with (escaped_parentheses)
- To escape curly braces take a look at the code:
echo \{One,Two,Three}" is a new file." #output: {One,Two,Three} is a new file.
This will prevent the expansion of the curly braces.
- Escape backslash by following the code:
echo "This is an example with an escaped backslash: \\" #output:This is an example with an escaped backslash: \
- To escape a backquoted operator use the following code:
echo "This is an example with \`escaped backquotes\`" #output: This is an example with `escaped backquotes`
Without the used backslash, it will show an error as the backquoted operator is used for command substitution.
-
Escape creating a new line in bash using the code below:
echo "This is a line with an escaped \ New started line." #output: This is a line with an escaped New started line.
This will not start a new line.
Now, here is an example bash script on how to escape dollar ($) or to prevent expansion with more details:
#!/bin/bash
str="This is a new string"
echo "This is a dollar sign: \$str"
The bash script declares a string in thestr
variable. In a normal scenario, the echo command would interpolate the variable value using$
. But the backslash prevents the interpretation of the expansion of the $ which is immediately after it.
The output keeps the literal values of the special character $ without any expansion.
2. Using Single Quotes
Single Quotes are used to create a string in which every character within the single quote is treated as a literal character. It is useful for including special characters or preventing misinterpretation.
To escape any special character you can use single quotes by using the following code:
#!/bin/bash
#Escaping using single quotes
echo '!It is a string that contains a special character @'
The bash script uses single quotes that keep the literal value of the!
and@
symbol.
From the output you can see, the single quotes treat each character with their literal meaning.
3. Using Double Quotes
Double Quotes are used to create a string that allows variable expansion, command substitution, and interpretation of escape characters within the string. To escape special characters such as space, hash, and single quotes you can use double quotes. Here is a bash script to demonstrate the process:
#!/bin/bash
#Escaping spaces
echo "This line has spaces."
#Escaping single quotes
echo "It's a new string with 'single quote'."
The double quote treats the space and single quotes as literal characters like other characters.
Using the double quotes, the output shows how you can escape spaces & single quotes in bash.
4. Using “printf” Command
The printf is a command line utility that is widely used to format and print text. To escape special characters the printf command with single and double quotes can be used. To escape the single quote using the printf command, follow the below:
#!/bin/bash
printf 'It%s a new string with %s.\n' "'s" "'single quote'"
In 'It%s a new string with %s.\n' "'s" "'single quote'"
, the printf
command formats the output and displays the output in the terminal. Here, the bash script uses the %s
as a placeholder. Then it uses \n at the end of the line which represents a new line character. Later the's
and'single quote'
will be inserted into the%s
placeholders.
From the image you can see, using the printf command’s formatting and double quotes, the bash script keeps the literal value of the single quotes.
5. Using ANSI-C Quoting
ANSI-C quoting is a form of special single quoting ($'...'
) that escapes sequences in bash. Here, the escape sequences start with a backslash (\
) character followed by a combination of characters. The bash script interprets the escape sequence inside the single quotes. Follow the code that has shown below:
#!/bin/bash
echo $'This is a string with ANSI-C escape sequences:\n\t- Newline\n\t- Tab\n\t- Single quote (\')\n\t- Double quote (")'
Inside the single quotes, the bash script interpreted the\n
as the newline character and\t
as a tab character. After that, the\'
represents a single quote in the string, and"
represents a double quote character.
From the image you can see, that the script prints the special character without its literal values.
Special Cases for Handling Special Characters
There may arise some problems that could be improved while handling some of the special characters. So, here are two of the problems with solutions discussed below:
Escaping “!” in Bash
While escaping the !
symbol in the terminal it may show an error. Because in the terminal when you are using!
symbol at the beginning or after a space then it will be considered as history expansion. To avoid this issue, take a look at the possible solutions below:
- Use a backslash immediately before the “!” symbol. However, the backslash (\) will remain in the output as a normal character.
- Use scripting to avoid this problem. Because when you are in bash scripting, you are in POXIS mode which does not allow history expansion.
- Disable the history expansion in the terminal.
To print the!
symbol at the beginning, you can use the following command in the terminal as it contains “!” at the beginning:
echo "!This is an exclamation mark: !"
From the image you can see, the terminal shows an error. To solve this error, now disable the history expansion by using the following command:
set +o histexpand
echo "!This is an exclamation mark: !"
set -o histexpand # Enable history expansion back if needed
This problem occurs in the terminal only, but if you try this in the scripting, it will not show this type of error.
Escape Single Quotes Inside Single Quotes
In bash scripting, you can escape single quotes inside a single quote by using only backslash as you can do inside the double quotes.
To escape single quotes within a single quote, use the following code:
#!/bin/bash
#Using backslash
echo 'It'"'"'s a new string with '\''single quote'\''.'
By following this method you can escape a single quote inside the single quotes.
Conclusion
This article shows how one can escape the characters which has some special meaning. From all the discussed methods except for escaping single quotes and exclamatory symbols, it is a wise & easy approach to use single quotes to escape characters as it considers the literal values of all characters. But if you want to escape specific characters then use the backslash. Hope you find this writing useful to understand how to escape special characters in bash.
People Also Ask
How can I escape double quotes?
To escape a double quote, you can use a single quote as it preserves the literal values of characters. If you use the double quote within the single quote it will escape the double quotes and will show the expected result. See the following code for better demonstration :
#!/bin/bash
echo 'This is a single-quoted string with a double quote: "Hello"'
#output: This is a single-quoted string with a double quote: "Hello"
How can I escape double quotes in double quotes?
To escape double quotes in double quotes, use the backslash immediately before each of the double quotes. Then the bash script will interpret the literal value of the double quote. Use the following code:
#!/bin/bash
echo "This is a double-quoted string with a double quote: \"Hello\""
#output: This is a double-quoted string with a double quote: "Hello"
Does Bash support hexadecimal or octal escape sequences for a single quote?
No, the single quote does not support the escape sequence including hexadecimal and octal in bash rather it preserves the literal value of each character.
How can I escape a backslash in bash?
To escape a backslash in a string, use backslash which will prevent the interpretation of the backslash, and print it as a literal character. Follow the code below:
#!/bin/bash
echo "This is an example with an escaped backslash: \\"
#output: This is an example with an escaped backslash: \
Related Articles
<< Go Back to Bash String Basics | Bash String | Bash Scripting Tutorial