Variables and Quoting

Notice that we used double quotes around variables (and strings containing them) in these echo examples. In Chapter 1, we said that some special characters inside double quotes are still interpreted, while none are interpreted inside single quotes.

A special character that "survives" double quotes is the dollar sign—meaning that variables are evaluated. It's possible to do without the double quotes in some cases; for example, we could have written the above echo command this way:

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

$ echo The value of \$
               varname 
               is \"$
               varname\".

But double quotes are more generally correct. Here's why. Suppose we did this:

$ fred='Four spaces between these words.'

Then if we entered the command echo $fred, the result would be:

Four spaces between these words.

What happened to the extra spaces? Without the double quotes, the shell splits the string into words after substituting the variable's value, as it normally does when it processes command lines. The double quotes circumvent this part of the process (by making the shell think that the whole quoted string is a single word).

Therefore the command echo "$fred" prints this:

Four spaces between these    words.

The distinction between single and double quotes becomes particularly important when we start dealing with variables that contain user or file input later on.

Double quotes also allow other special characters to work, as we'll see in Chapter 4, Chapter 6, and Chapter 7. But for now, we'll revise the "When in doubt, use single quotes" rule in Chapter 1 by adding, "...unless a string contains a variable, in which case you should use double quotes."