dcsimg

Single vs. Double Quotes in Bash

By Juliet Kemp (Send Email)
Posted Aug 23, 2010


More on Bash

In Bash, whether to use single or double quotes depends on exactly what you want to do, and the differences can trip you up if you're not concentrating. Here's a quick rundown of what each does and when to use them.

When using Bash, the decision to use single quotes or double quotes depends on exactly what you want to do. Find out what each does and when to use them.

Double quotes are the less restrictive option. Within a double-quoted string, the only special characters that are reinterpreted are $, ` (backquote), and (the escape character). Double quotes are useful when using variables (in case the variable uses other special characters), or to avoid whitespace being used to make one argument into two. For example:

message="My commit message"
git commit -m $message

Here, $message will be interpreted as three separate words, so the only part that will be used as the commit message is "My". "commit" and "message" will be treated as files to look for, and the commit will probably fail. Use double quotes to fix this:

message="My commit message"
git commit -m "$message"

This is also useful on the control line if you have filenames with spaces in: Using double quotes avoids the spaces being interpreted as creating multiple filenames. You can also avoid expanding * by using double quotes. I find this handy when using dpkg-query -l term* to search for particular packages. If there's a file called term* in the directory, Bash will expand the * before calling dpkg-query, messing up your search. Use dpkg-query -l "term*" to get the result you want.

Single quotes are stricter. The only special character that is recognized within single quotes is ' (as the end of the quote section). So:

name="Juliet Kemp"
echo "$name" # Outputs Juliet Kemp
echo '$name' # Outputs $name

Single quotes are great if you've got lots of special characters and want them all to be used 'straight.' However, it's no good when you're dealing with variables that you do want to dereference. You must keep those outside the single quotes. Note as well that you can't use a single quote inside a single-quoted string. For that, you must use double quotes.

Using double quotes around variables is a good habit to get into; single quotes are likely to be useful in fewer situations, although they do have their place.

Juliet Kemp has been messing around with Linux systems, for financial reward and otherwise, for about a decade. She is also the author of "Linux System Administration Recipes: A Problem-Solution Approach" (Apress, 2009).

Follow ServerWatch on Twitter

Page 1 of 1


Comment and Contribute

Your name/nickname

Your email

(Maximum characters: 1200). You have characters left.