Mika H.
Mika H.

Reputation: 4329

grep pattern single and double quotes

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 :)

Upvotes: 6

Views: 3164

Answers (2)

Zhenhua
Zhenhua

Reputation: 2579

  • 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.

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185053

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.

Upvotes: 6

Related Questions