Skip to content

How to escape characters in the command line?

Escape Characters

This article on escape characters is a natural continuation of the last, which dealt with the echo method. If you, still can’t fully grasp the notion of the echo I fully encourage you to first read that article, and then come back.

Done?

Amazing – now let us look at the following command-line snippet:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ echo "The bananas are $2.99"
> "The bananas are .99"
$ echo "The bananas are $2.99" > "The bananas are .99"
$ echo "The bananas are $2.99" 
> "The bananas are .99"

The $ inside commands serves different roles including parameter expansion, command substitution, or arithmetic expansion. In our specific case, we try to retrieve a variable inside the echo parameter – the dollar sign is connected to the number 2 which the shell interprets as a variable. But behold – there is no such variable, so the parameter expansion returns an empty string. Compare this to the snippet below:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ 2=number
$ echo $2
> "number"
$ echo "The bananas are $2.99"
> "The bananas are number.99"
$ 2=number $ echo $2 > "number" $ echo "The bananas are $2.99" > "The bananas are number.99"
$ 2=number

$ echo $2
> "number"

$ echo "The bananas are $2.99"
> "The bananas are number.99"

Here we actually set the variable 2 to the value ‘number’. The next time we try to retrieve that variable using $2 we get the message “The bananas are number.99”.

How to escape special characters?

In order to prevent any expansion we precede a (special) character with a backslah, which is called the escape character in that specific context. We also use the escape character to eliminate characters that have special meanings inside filenames.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ echo "The bananas are \$2.99"
> "The bananas are $2.99"
$ buyer=Sean
$ echo "$buyer bought bananas for \$2.99"
> "Sean bought bananas for $2.99"
$ echo "The bananas are \$2.99" > "The bananas are $2.99" $ buyer=Sean $ echo "$buyer bought bananas for \$2.99" > "Sean bought bananas for $2.99"
$ echo "The bananas are \$2.99"
> "The bananas are $2.99"

$ buyer=Sean

$ echo "$buyer bought bananas for \$2.99"
> "Sean bought bananas for $2.99"

To escape the backslash itself we just write “\\”.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ echo "The fraction 1\\2 is 0.5"
> "The fraction 1\2 is 0.5"
$ echo "The fraction 1\\2 is 0.5" > "The fraction 1\2 is 0.5"
$ echo "The fraction 1\\2 is 0.5"
> "The fraction 1\2 is 0.5"

Final Words

Hope you learned something interesting regarding escape characters, please check some more Linux articles by clicking down below.