Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

In this command:

find . -name \*.pyc -delete

Why is a backslash needed before *.pyc ?

share|improve this question
    
The man page for find should have a section called NON-BUGS with something similar as an example and an explanation of why it is needed. –  Brian May 4 at 13:37

2 Answers 2

up vote 17 down vote accepted

An unquoted glob would be expanded by the shell before find is executed. (Refer to Filename Expansion in the manual.)

So saying:

find . -name *.pyc -delete

would actually execute:

find . -name file1.pyc file2.pyc file3.pyc -delete

assuming there were 3 .pyc files in the current directory and result in an error instead.

A backslash makes the shell pass the glob to find, i.e. it acts as if *.pyc were quoted.

Ideally, you should be quoting a glob:

find . -name '*.pyc' -delete
share|improve this answer
    
Thanks for the quotes tip, it's indeed more pretty. –  Ram Rachum May 4 at 14:11
    
@RamRachum, but more character when typing. –  Paul Draper May 5 at 0:39
1  
@PaulDraper Readable and less prone to mistakes > Shorter by one keystroke –  Doorknob 冰 May 5 at 1:17
    
Single quotes are the way to go. I never even thought you could use the backslash in this way... –  Floris May 5 at 4:45

Before your shell issues the find command, it will do various expansions. Doing so, it also processes special characters (or, characters with special meaning), where * is a wildcard – a globbing character. This is the so-called filename expansion.

Say you have two files in your directory:

  • foo.pyc
  • bar.pyc

Then *.pyc would expand to both names. So if you write:

find . -name *.pyc -delete

then the shell will actually call:

find . -name foo.pyc bar.pyc -delete

which does not make a lot of sense, because you can only have one argument for -name. That's why you need to escape the special character to prevent it from being interpreted by the shell. You do that by backslash-escaping, or alternatively, quoting it.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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