Finding Files by Type

Problem

You are looking for a directory with the word “java” in it. When you tried:

$ find . -name '*java*' -print

you got way too many files—including all the Java source files in your part of the filesystem.

Solution

Use the -type predicate to select only directories:

$ find . -type d -name '*java*' -print

Discussion

We put the -type d first followed by the -name *java*. Either order would have found the same set of files. By putting the -type d first in the list of options, though, the search will be slightly more efficient: as each file is encountered, the test will be made to see if it is a directory and then only directories will have their names checked against the pattern. All files have names; relatively few are directories. So this ordering eliminates most files from further consideration before we ever do the string comparison. Is it a big deal? With processors getting faster all the time, it matters less so. With disk sizes getting bigger all the time, it matters more so. There are several types of files for which you can check, not just directories. Table 9-1 lists the single characters used to find these types of files.

Table 9-1. Characters used by find’s -type predicate

Key

Meaning

b

block special file

c

character special file

d

directory

p

pipe (or “fifo”)

f

plain ol’ file

l

symbolic link

s

socket

D

(Solaris only) “door”

See Also

  • man find

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.