17

I know that we can escape a special character like *(){}$ with \ so as to be considered literals.
For example \* or \$

But in case of . I have to do it twice, like \\. otherwise it is considered special character. Example:

man gcc | grep \\.

Why is it so?

2 Answers2

28

Generally, you only have to escape one time to make special character considered literal. Sometime you have to do it twice, because your pattern is used by more than one program.

Let's discuss your example:

man gcc | grep \\.

This command is interpreted by two programs, the bash interpreter and grep. The first escape causes bash to know \ is literal, so the second is passed for grep.

If you escape only one time, \., bash will know this dot is literal, and pass . to grep. When grep see this ., it thinks the dot is special character, not literal.

If you escape twice, bash will pass the pattern \. to grep. Now grep knows that it is a literal dot.

slm
  • 369,824
cuonglm
  • 153,898
  • :So,Does the escape character for dot depends on the number of pipes we use?.For example cmd | cmd | cmd | cmd \\. Is that correct???? – Thushi Jul 16 '14 at 06:49
  • 7
    @Thushi: No. This has nothing to do with the fact that you are using a (or several) pipe characters, but applies even for grep \\. my_file. The commandline is interpreted by the shell, using the first \ to escape the second one, so one \ is passed literally to grep. The dot . is not special to the shell, so it is passed verbatim anyway. Grep then reads the (single) \ and uses it to escape the dot .. – Ansgar Esztermann Jul 16 '14 at 06:59
  • @AnsgarEsztermann: Yes.That's true.Checked it.Thanks :) – Thushi Jul 16 '14 at 07:03
  • 2
    I believe the answer is somewhat incorrect in that it says "The first escape causes bash knows . is literal, the second is for grep.". Actually, the first escape lets bash know that \ is leteral, and pass . to grep. – Cthulhu Jul 16 '14 at 08:37
  • @Gnouc I don't think it has. echo . in the bash just... echoes bach . character. – Cthulhu Jul 16 '14 at 08:54
  • @Cthulhu: Oh, my bad, updated. – cuonglm Jul 16 '14 at 09:00
  • @Emmanuel: After Cthulhu's comment, see above. – cuonglm Jul 16 '14 at 09:13
  • @gnouc Ok sorry, I missed it – Emmanuel Jul 16 '14 at 09:18
0

To prevent bash from trying to interpret your arguments, enclose them in quotes

man gcc | grep "\."
Rucent88
  • 1,880
  • 4
  • 24
  • 37
  • In general, it would be better to use single quotes as backslash is still special within double quotes (though not when followed by .) in Bourne-like shells. Or use grep -F .. BTW, the OP made no mention of the bash shell. Not all shells treat backslash or "..." as quoting operators. rc doesn't for instance (same comment applies to the accepted answer). – Stéphane Chazelas Aug 16 '21 at 10:07