6

When writing a Bash script that contains messages for the user, I can write

echo Processing files...

or

echo "Processing files..."

In this and many other cases, the output will be the same. So when do I actually need double quotes, and when may they be unnecessary?

I understand that

echo This    is     my      sentence.

and

echo "This    is     my      sentence."

will produce different outputs (single space between words in first case, spacing retained in second case), but are there other reasons to use double quotes? Or not to use double quotes?

(I realize that single quotes have a different effect; this question is specifically about double quotes.)

Chad
  • 1,461

2 Answers2

4

There are lots of reasons, but the main ones:

  • better control over the inclusion of whitespace (which you noticed)
  • partial protection against unexpected shell expansion, e.g., of glob characters * and ?
Thomas Dickey
  • 76,765
  • Though ` (backtick), $, and \ (escape) will still be recognized in double quotes.

    Reference: http://tldp.org/LDP/abs/html/quotingvar.html

    – StevieD Aug 28 '18 at 02:34
  • TLDP is known as a poor information resource. I found an error in the page linked above.  And it refers to the \ character as “escape”, which is not really standard and is especially confusing when it also uses “escape” as a verb. – G-Man Says 'Reinstate Monica' Jul 14 '20 at 03:09
0

There is an important difference between double-quotes and single-quotes here. The double quotes will interpolate variables inside the quoted string (as will not quoting at all); single quotes will not do so.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
John
  • 17,011
  • agreed, but OP asked about double-quotes, which do have their place in scripting. I marked it to close as well, but this is one of those cut/paste magnets... – Thomas Dickey Mar 11 '16 at 19:10