ericj
ericj

Reputation: 2301

Must special characters in bash double quoted or escaped with \

Should I double quote or escape with \ special characters like ',

$ echo "'"
'
$ echo \'
'

Here is apparently doesn't matter, but are there situations where there is a difference, except for $, `` or`, when I know there is a difference.

Thanks,

Eric J.

Upvotes: 1

Views: 450

Answers (1)

David W.
David W.

Reputation: 107090

You can use either backslashes, single quotes, or (on occasion) double quotes.

Single quotes suppress the replacement of environment variables, and all special character expansions. However, a single quote character cannot be inside single quotes -- even when preceded by a backslash. You can include double quotes:

$ echo -e 'The variable is called "$FOO".'
The variable is called "$FOO".

Double quotes hide the glob expansion characters from the shell (* and ?), but it will interpolate shell variables. If you use echo -e or set shopt -s xpg_echo, the double quotes will allow the interpolation of backslash-escaped character sequences such as \a, and \t. To escape those, you have to backslash-escape the backslash:

$ echo -e "The \\t character sequence represents a tab character."
The \t character sequence represents a tab character."

The backslash character will prevent the expansion of special characters including double quotes and the $ sign:

$ echo -e "The variable is called \"\$FOO\"."
The variable is called "$FOO".

So, which one to choose? Which everyone looks the best. For example, in the preceding echo command, I would have been better off using single quotes and that way I wouldn't have the confusing array of backslashes one right after another.

On the other hand:

$ echo -e "The value of \$FOO is '$FOO'."
The value of FOO is 'bar'.

is probably better than trying something like this:

$ echo -e 'The value of $FOO is '"'$FOO'."

Readability should be the key.

Upvotes: 1

Related Questions