85

I am running the following command, but it is not performed recursively:

find . -name *.java

I know there are java files further down in the current directory but it is performing the find on the current directory only. I am using OS X, 10.9.

0

3 Answers 3

113

The problem is, you didn't quote your -name parameter. Do this instead:

find . -name '*.java'

Explanation

Without the quotes, the shell interprets *.java as a glob pattern and expands it to any file names matching the glob before passing it to find. This way, if you had, say, foo.java in the current directory, find's actual command line would be:

find . -name foo.java

which would obviously list the file in the current directory only (unless you happen to have some similarly-named files further down the tree).

Quoting prevents glob expansion and passes the command line to find as-is.

Incidentally, if the glob had failed to match (no *.java files in the current directory), you would get one of two behaviors depending on how your shell is set up to handle globs that don't match (this is governed by the nullglob option in Bash, for example):

  1. If a glob that doesn't match is not expanded by the shell, find will (accidentally, mind you) exhibit correct behavior.
  2. If a glob that doesn't match is expanded into an empty string by the shell, find will complain that it is missing an argument to -name.
1
  • Along with this, it is important to note how to include soft-linked subdirectories - for which 'gaoagong' answer below was an extreme lifesaver for me.
    – KGhatak
    Nov 16, 2021 at 10:35
30

I had a situation similar where I was surrounding the -name value in quotes, but still wasn't getting all of the find hits that I was hoping for. I conjectured that it was because of symlinks and sure enough that was the case. If you want to force find to search through symlinks you can modify the command to the following:

find -L . -name '*.java'
2
  • 3
    Symlinks were my issue too. -follow is a more readable synonym for -L, as long as you put it before the other params.
    – Noumenon
    Aug 1, 2019 at 1:48
  • Great! Thanks a lot!! +1!
    – rmbianchi
    Aug 5, 2020 at 13:52
1

Escape the *

find . -name \*.java

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.