问题
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 :)
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/13282860/grep-pattern-single-and-double-quotes