| Lesson 7 | Finding files |
| Objective | Use the find command to search for files. |
When you know where a file is stored, listing its directory is usually enough to locate it. When you know only part of its name, or remember that it belongs somewhere within a project, use find. This command searches a directory hierarchy and selects entries according to criteria you provide. It can locate documents, images, directories, and other filesystem objects without requiring you to open each directory separately.
In this lesson, you will choose a starting directory, list its contents recursively, select regular files or directories, match filename patterns, and save the results. These examples use familiar UNIX command syntax available on Linux and other UNIX-like systems. They search for filesystem entries, not words inside documents. Finding a file named report.txt and searching that file's contents are different tasks.
The following is a syntax template, not a command to type literally:
find path... [expression]
The path... notation means one or more starting paths. The optional expression describes what to select and what to do with each matching entry. For example, -type f is a test for a regular file, while -print is an action that displays its pathname. Put the starting paths before the expression.
find images -type f -print
Read this command from left to right: start at images, examine that directory and the entries beneath it, select regular files, and print their paths. Searching subdirectories is called a recursive search. You do not need to name every subdirectory yourself. The starting entry is also examined, although it appears in the results only if it passes the tests.
A relative path such as images is interpreted from your current working directory. An absolute path such as /usr/share starts at the filesystem root. The special path . means the current directory. If a relative path seems wrong, use pwd to check where you are before changing the search.
Suppose your working directory contains the following entries:
$ ls -F
ex200-1 images/ practice/ project/ qa.html@
The $ represents a shell prompt; do not type it. The -F option adds indicators to this listing: a trailing slash marks a directory, and @ marks a symbolic link. These indicators are not part of the names you supply to find. The commands below omit prompts so you can copy them directly.
find images -print
For the example directory tree, the output is:
images
images/bullets
images/bullets/ballblue.gif
images/bullets/ballred.gif
images/bullets/ballyell.gif
images/icons
images/icons/logo1.jpg
images/icons/logo_big.jpg
images/icons/down.gif
images/icons/up.gif
images/lines
images/lines/thick.gif
images/lines/thin.gif
images/lines/rainbow.gif
The first line is images itself. The remaining lines include subdirectories and files within them. Unlike a basic listing of the current directory, this search exposes the nested structure. Each printed path tells you how to reach the entry from the working directory where you ran the command.
All output in this lesson illustrates the sample tree. Your own results depend on the files present and your access permissions. Traversal order can differ, so do not assume that find sorts results alphabetically or always prints them in the exact sequence shown here.
To see only directories, add the -type d test:
find images -type d -print
images
images/bullets
images/icons
images/lines
The starting directory passes this test, so it remains in the output. The image files do not pass and are omitted. This is useful when you want to understand a folder structure without reviewing every document or image stored within it. It also demonstrates an important distinction: a test filters results; it does not automatically stop traversal.
Use -type f when you want regular files, such as documents, scripts, and images:
find images -type f -print
images/bullets/ballblue.gif
images/bullets/ballred.gif
images/bullets/ballyell.gif
images/icons/logo1.jpg
images/icons/logo_big.jpg
images/icons/down.gif
images/icons/up.gif
images/lines/thick.gif
images/lines/thin.gif
images/lines/rainbow.gif
The directories disappear from the printed list, but find still visits them to reach their contents. The letter f means regular file, not every kind of filesystem object. Directories and symbolic links are separate types. With the default link handling used here, find does not follow symbolic links encountered during traversal; a link to a regular file is not itself selected by this test.
Choosing the type explicitly makes your intention clear. A name that ends in .jpg could belong to a directory, and a regular file does not need an extension. File type and filename are independent properties, so a filename pattern alone does not establish what kind of entry you found.
The -name test checks an entry's basename, which is its name without the preceding directories. To select names ending in lowercase .jpg, use:
find images -name '*.jpg' -print
images/icons/logo1.jpg
images/icons/logo_big.jpg
Here, * matches zero or more characters. The pattern is a shell-style filename pattern, not a regular expression. Matching is case-sensitive: logo.JPG does not match *.jpg. Because -name tests the basename, do not include the parent directories in this pattern.
The single quotes protect the wildcard from expansion by your shell. Without them, the shell might replace *.jpg with matching names in your current directory before find starts. The resulting command could fail or search for something different. Quoting ensures that find receives one pattern to apply throughout the tree. The GNU manual describes this behavior under base name patterns.
To require both a matching name and a regular file, combine the tests:
find images -type f -name '*.jpg' -print
Adjacent tests in this expression use an implicit AND: the entry must be a regular file and its name must match. For the illustrated tree, the results are unchanged. If a directory named old.jpg were present, the combined expression would exclude it. This is a useful habit when the task specifically asks for files rather than any matching entry.
The output of find can be redirected into a text file instead of appearing in the terminal:
find images -name '*.jpg' -print > JPG_list
The shell interprets >. It creates JPG_list if necessary or replaces its existing contents. After the command finishes, inspect the saved list with:
cat JPG_list
The file contains the matching pathnames, not copies of the images. Those relative paths make sense from the original working directory, so remember that context if you move the report elsewhere. In this example, the report is outside the images directory being searched.
A successful redirection leaves the terminal without the usual matching-path output. An empty report can mean that no entries matched, but it does not prove the search completed successfully. Errors are normally written to standard error and remain visible in the terminal. Read any messages before concluding that a file does not exist. Also choose the report filename carefully because > overwrites existing content.
When you want to include all accessible subdirectories beneath your working directory, use . as the starting path:
find . -name '*.html' -print
./project/docs/index.html
./project/docs/doc_plan.html
./project/mktg/index.html
./project/mktg/requirements.html
./project/qa/index.html
./project/qa/test_plan.html
./project/sw/index.html
./project/sw/product_spec.html
./project/index.html
./.stuff/index.html
./.stuff/index_results.html
./test.html
The leading ./ means each path is relative to the current directory. Notice the results under .stuff, a directory whose name begins with a dot. A plain ls normally hides such names, but recursive traversal by find includes hidden directories. Searching from . therefore covers more than the entries visible in a basic listing.
This command has one starting path. To search two specific trees instead, place both paths before the tests:
find images project -type f -print
This searches regular files beneath images and project without searching the separate practice directory. Choosing narrower starting points can make results easier to interpret and avoid unnecessary traversal. A path containing spaces must be quoted, just as you would quote it in other shell commands.
If a search produces no matches, check the starting directory, spelling, capitalization, and quotes. Try listing the tree with find images -print before adding filters. Then add -type or -name one at a time. This separates a wrong starting point from a pattern that excludes the file you expected.
A permission error means part of the search could not be completed. Results from accessible directories may still appear, so a partial list is possible. Start with a directory you own or are authorized to read. Do not automatically hide diagnostics or rerun a broad search with elevated privileges. A live filesystem can also change while the search runs; the output describes what the command encountered rather than a permanent inventory.
The examples write -print explicitly to make the output action visible. Simple searches on modern implementations also print matching entries by default when no action overrides that behavior. This convenience is not unique to SunOS. When reading more complex commands, check their actions rather than assuming that default printing always applies.
For additional details, run man find on your system. Beyond names and types, find can test ownership and modification times. Learn those features when a task requires them; the essential sequence remains choosing starting paths, expressing selection criteria, and deciding how to use the results.
Practice the file-link concepts from the previous lesson and the searches introduced here in the Finding Unix Files - Exercise. Before running each search, identify its starting path and predict which entries should match. Compare your prediction with the output, including whether directories or hidden paths appear.
The next lesson reviews this module's file-management commands, terms, and concepts and leads into the module quiz.