Search code examples
shellgrepdouble-quotessingle-quotes

What's the differences between grep '\$' and grep "\$"?


What's the differences between grep '\$' and grep "\$"?

Could someone give a proper explanation for the below command.

/usr/download/test/myshell$ cat a_file
boot
book
booze
machine
boots
bungie
bark
aardvark
broken$tuff
robots

Output: grep '\$' a_file

/usr/download/test/myshell$ grep '\$' a_file 
broken$tuff

Output: grep "\$" a_file

/usr/download/test/myshell$ grep "\$" a_file 
boot
book
booze
machine
boots
bungie
bark
aardvark
broken$tuff
robots

Output: grep \$ a_file

/usr/download/test/myshell$ grep \$ a_file 
boot
book
booze
machine
boots
bungie
bark
aardvark
broken$tuff
robots

Solution

  • \ is an escape character for both bash and grep.

    • In grep \$ a_file, bash thinks you are escaping $, but it doesn't need escaping, so the regexp being executed is $, which looks for any line that has an end (unsurprisingly, all of them do).

    • In grep "\$" a_file, bash interprets double quotes, which allow a variety of bashy things to go on inside. Specifically, it still allows bash escapes, just like above; the command being executed is again $.

    • In grep '\$' a_file, bash interprets single quotes, which basically tell bash to keep things inside intact as much as possible. Notably, bash will not remove the backslash. The regexp will be \$, where \ removes the special meaning of "end of line" from the dollar, and a literal dollar character is being searched for.

    See man bash under QUOTING for more details.