1

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
ping chang
  • 35
  • 1
  • 4
  • Does this answer your question? [grep pattern single and double quotes](https://stackoverflow.com/questions/13282860/grep-pattern-single-and-double-quotes) – Reza Dehnavi Nov 28 '19 at 04:40

1 Answers1

2

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

Amadan
  • 191,408
  • 23
  • 240
  • 301