13

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?

  • Can you give the case that you have to escape twice? – cuonglm Jul 16 '14 at 6:29
  • man bash|grep \\. could be a example. – Registered User Jul 16 '14 at 6:31
  • 3
    More precisely, you do not escape dot twice, you escape the escape character so that it gets passed to grep – Cthulhu Jul 16 '14 at 8:46
  • 5
    You could use quotation marks to avoid escaping backslash characters: man gcc | grep '\.'. – Leonid Beschastny Jul 16 '14 at 10:21
  • 1
    I strongly prefer @LeonidBeschastny's suggestion because of how much clearer it is what's going on – Izkata Jul 16 '14 at 13:58
24

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 disscuss your example:

man gcc | grep \\.

This command is interpreted by two programs, bash interpreter and grep. The first escape causes bash knows \ is literal, so the second is pass 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 pattern \. to grep. Now grep know that it is a literal dot.

  • :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 6:49
  • 6
    @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 6:59
  • @AnsgarEsztermann: Yes.That's true.Checked it.Thanks :) – Thushi Jul 16 '14 at 7: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 8:37
  • @Gnouc I don't think it has. echo . in the bash just... echoes bach . character. – Cthulhu Jul 16 '14 at 8:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.