Unix How-To: Quotes to Live By

One of the things that really throws new Unix users is when to use quotes and which kind of quotes. Between single quotes, double quotes and back ticks, a person can start to feel that Unix is unnecessarily tricky.

Double quotes are the easiest to understand. Unlike Windows, the only way to work on the command line with files whose names contain blanks (e.g., "my file") is to enclose the file names in some kind of quotes. If you want to echo text to a user containing strings of consecutive blanks (e.g., "first second"), you need the quotes, else you get "first second".

You might also use double quotes to keep apostrophes (i.e., single quotes) from being interpreted by the shell as the beginning of strings. If you type a phrase containing an apostrophe, Unix will keep looking for the matching end of quote and will prompt with its secondary prompt (usually a ">"):

$ echo What's wrong now?

Of course, you can always "escape" the apostrophe so that the shell doesn't react to it as if it were a delimiter. But a user who can anticipate the need for an escape is probably one who will know when to enclose strings in double quotes in the first place.

$ echo what\'s wrong now?
what's wrong now?

Single quotes work the same as double quotes except for one very significant difference. Double quotes allow variables within to be resolved; single quotes do not. So, echo "Hello, $USER" becomes Hello, jdoe, while echo 'Hello, $USER' displays Hello, $USER. If you want to redirect a statement such as Hello, $USER to a script, it makes a big difference which form you use.

One common use of both double and single quotes is to prevent a variable, which just might have a value with embedded quotes, from disrupting an if statement. The code below looks innocuous enough, but if the variable $var2 gets a value of "10 days" instead of "10", the if statement breaks.

if [ $var2 == 10 ]; then

Putting quotes around $var2 would prevent this kind of thing from happening.

if [ '$var2' == 10 ]; then

Back ticks have an altogether different purpose altogether. They are used to invoke a command, replacing the command in a line of text with the command's output. You can type:

$ echo Today is `date +%A`

The output will be of the form "Today is Wednesday".

Even an experienced Unix user will trip over quote problems now and then. But echo "That's Life!".

Join the Network World communities on Facebook and LinkedIn to comment on topics that are top of mind.
Now read: Getting grounded in IoT