6

Is there any difference between enclosing grep patterns in single and double quotes?

grep "abc" file.txt

and

grep 'abc' file.txt

I'm asking since there's no way I could test all possible cases on my own, and I don't want to stumble into a case that I get wrong :)

Mika H.
  • 4,119
  • 11
  • 44
  • 60

2 Answers2

6

I see a difference if you have special characters :

Ex :

grep "foo$barbase" file.txt

The shell will try to expand the variable $barbase, this is maybe not what you intended to do.

If instead you type

grep 'foo$barbase' file.txt

$bar is taken literally.

Finally, always prefer single quotes by default, it's stronger.

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • 1
    Finally, always prefer simple quotes by default, it's stronger. -> You mean single quotes, right? :) – Mika H. Nov 08 '12 at 05:36
1
  • In double quote, the following characters has special meanings: ‘$’, ‘`’, ‘\’, and, when history expansion is enabled, ‘!’.

    The characters ‘$’ and ‘’ retain their special meaning within double quotes ($ for variables and for executing).

    The special parameters ‘*’ and ‘@’ retain their special meaning in double quotes as inputs when proceeded by $.

    ‘$’, ‘`’, ‘"’, ‘\’, or newline can be escaped by preceding them with a backslash.

    The backslash retains its special meaning when followed by ‘$’, ‘`’, ‘"’, ‘\’, or newline. Backslashes preceding characters without a special meaning are left unmodified.

    Also it will be helpful to check shell expansions:
    https://www.gnu.org/software/bash/manual/html_node/Shell-Expansions.html#Shell-Expansions

  • Single quote ignore shell expansions.
Zhenhua
  • 2,389
  • 15
  • 10