grep pattern single and double quotes

◇◆丶佛笑我妖孽 提交于 2021-02-07 14:26:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!