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:
$ 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:
$ 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.
$ 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 “\\”.
$ 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.