Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 '14 at 13:37
up vote 18 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 '14 at 14:11
    
@RamRachum, but more character when typing. – Paul Draper May 5 '14 at 0:39
1  
@PaulDraper Readable and less prone to mistakes > Shorter by one keystroke – Doorknob May 5 '14 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 '14 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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .