19

This one is correct:

$ find . -name *main.o
./main.o

So, why I can't find *.o?

$ find . -name *.o
find: paths must precede expression: main.o
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
Eliah Kagan
  • 116,445
  • 54
  • 318
  • 493
The Student
  • 11,786
  • 27
  • 61
  • 94
  • 2
    Duplicate of http://askubuntu.com/questions/112722/command-find-name-must-be-enclosed-in-quotes-or-it-doesnt-work-why-is-that?rq=1? – T.J. Crowder Oct 17 '14 at 11:05
  • The one you call correct is also wrong. If there is one match in the current directory and another match in a subdirectory, it will not be able to find both unless both happen to have the same name. I.e. in your first example there could have been a file called `./sub/domain.o`, which it did not find. – kasperd Oct 17 '14 at 15:25

2 Answers2

46

Probably there are more than one file that match *.o, while only one file match *main.o, so, in the first case, shell expansion runs:

$ find . -name main.o

and this works. In the second case:

$ find . -name file1.o main.o

And this is why you got error.

In order to prevent this, you should quote expression in both command:

$ find . -name '*.o'
$ find . -name '*main.o'
Lety
  • 5,994
  • 2
  • 28
  • 36
  • 2
    Indeed, one can easily check this with `echo *.o` vs `echo '*.o'`. – Ruslan Oct 16 '14 at 17:06
  • @Ruslan Depends, if there are no files matching the glob (`*`, `?`) bash will treat it as the literal character. –  Oct 22 '14 at 05:18
  • @BroSlow undoubtedly, I was talking about the particular situation the OP was in. – Ruslan Oct 22 '14 at 06:54
16

Put the file pattern in quotes. Otherwise, * is expanded by the shell (resolved to a list of files before find sees it), confusing find.

find . -name "*.o"
Stefan Haustein
  • 801
  • 6
  • 7