Escaping characters in shell scripting

Escaping is a method of quoting single characters. The escape (\) preceding a character tells the shell to
interpret that character literally.

With some commands, like sed and echo, for example, the escaping has the opposite effect, it toggles on special characters. I have discussed about these special characters with the echo command here.

With some commands and utilities, such as echo and sed, escaping a character may have the opposite
effect, it can toggle on a special meaning for that character:

  • \n  – new line
  • \r  – return
  • \t  – tab
  • \v  – vertical tab
  • \b  – backspace
  • \a  –  alert, beep or flash

Examples :

Use -e to enable the special characters:

$ echo -e "\t\tText here" #this inserts two tabs before the text

$ echo -e "\n\nText here" #this inserts two new lines before the text

This will make the -e option unnecesarry: $’/Text’

$ echo $'\nText here' # this is the same as echo -e "\nText here"

How to display falues between double quotes with echo:

The double quotes you want to display need to be escaped: “\”escape”\”

$ echo "escape"
escape
$ echo "\"escape"\"
"escape"

How to escape the $ special character: \$

$ echo "The \"Linux\" book cost \$7.98."
The "Linux" book cost $7.98.

The escape character is also used to write a long command on more than one lines.
When the shell meets \, it reads the next line as it was on the current line:

$ echo foo\
> bar
foo bar

$ echo "foo\
> bar"
foo bar

Related reading: Quoting in shell scripting

If you liked this article, read the other bash scripting articles.

Tagged with: , , , , , ,
Posted in The Linux and Unix Articles!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Subscribe

  

Subscribe to get the latest Linux news and how to guides directly on your e-mail!