Special Characters and Quoting in Shell Script
With the exception of the letters and the digits, practically every key on the keyboard is a metacharacter in some context or other (including the space, the tab, and the newline). A metacharacter is a character that represents something other than its literal self.
When you want a metacharacter to be taken literally, you must tell the shell to leave it alone (rather than interpreting it) by using one of the three following mechanisms:
- Single quotes, which turn off the special meaning of all characters
- Double quotes, which turn off the special meaning of characters except $, ‘,", and \
- Backslash, which turns off the special meaning of the following character
A Pair of Single Quotes
A pair of single quotes, ’…’, turns off the special meaning of all characters enclosed by the single quotes, including the \ character.
$ echo a b a b $ echo ’a b’ a b $ num=25 $ echo ’The value of num is $num’ The value of num is $num
A Pair of Double Quotes
A pair of double quotes (as in “…”) turns off the special meaning of all characters enclosed by the double quotes, except for the four characters $, ‘, “, and \. Within double quotes, use the backslash to selectively turn off the special meaning of these four characters.
$ num=25 $ echo "The value of num is $num" The value of num is 25 $ name=Roger $ echo "Hi $name, I’m glad to meet you!" Hi Roger, I'm glad to meet you! $ echo "Hey $name, the time is ‘date‘" Hey Roger, the time is Fri Jul 9 16:52:50 PDT 1999
If you need to have the special meaning of any character turned off and the character to have its literal value, precede it with the backslash (\) character, which is often called an escape character. Use the backslash to turn off the special meaning of any shell metacharacter.
$ name=jessica $ echo "Hello $name. \ > Where are you going?" Hello jessica. Where are you going? Include the backslash (\) character before $name. $ echo "Hello \$name. \ > Where are you going?" Hello $name. Where are you going?
The eval Command
The eval command reads its arguments as input to the shell and executes the resulting command(s). This is usually used to execute commands generated as the result of command or variable substitution.
$ eval whence -v ps ps is /usr/bin/ps