← Back to Bash Course | Chapter 9: File Testing & Filesystem | Lesson 12 of 13

find Command Basics

The find command searches through directories to locate files and folders that match criteria you give it, like name or type.

Finding Files by Name

find dir -name "pattern" recursively searches dir for entries whose name matches the quoted glob pattern. Quoting prevents the shell from expanding the pattern itself before find runs.

Example: Finding Files by Name

bash
#!/bin/bash
mkdir -p search_demo/sub
touch search_demo/a.txt search_demo/sub/b.txt search_demo/c.log
find search_demo -name "*.txt"
rm -rf search_demo

Filtering by Type

-type f matches only regular files and -type d matches only directories, letting you narrow a search when names alone are not specific enough.

Example: Filtering by Type

bash
#!/bin/bash
mkdir -p type_demo/inner
touch type_demo/file.txt
find type_demo -type d
echo "---"
find type_demo -type f
rm -rf type_demo

Running a Command on Each Match

-exec command {} \; runs command once for each matched file, substituting {} with the file's path. Ending with + instead of \; batches as many matches as possible into fewer command invocations, which is faster for large result sets.

Example: Running a Command on Each Match

bash
#!/bin/bash
mkdir -p exec_demo
touch exec_demo/one.txt exec_demo/two.txt
find exec_demo -type f -name "*.txt" -exec echo "found: {}" \;
rm -rf exec_demo

Limiting Search Depth

-maxdepth N limits how many directory levels find descends into, which is useful when you only want the current directory's immediate contents rather than a full recursive search.

Example: Limiting Search Depth

bash
#!/bin/bash
mkdir -p depth_demo/nested
touch depth_demo/top.txt depth_demo/nested/deep.txt
echo "maxdepth 1:"
find depth_demo -maxdepth 1 -type f
echo "no maxdepth limit:"
find depth_demo -type f
rm -rf depth_demo
Common Mistakes
  1. Forgetting find searches recursively into subdirectories by default, which can be slower or broader than expected on large trees.
  2. Not quoting the -name pattern, letting the shell expand it as a glob before find even sees it.
  3. Using find ... -exec cmd {} \; without realizing it runs cmd once per file, which is slower than -exec cmd {} + for large result sets.
Chapter Summary
  • find dir -name pattern searches recursively for names matching a quoted glob pattern.
  • -type f restricts results to regular files, -type d to directories.
  • find ... -exec cmd {} \; runs a command once per matched file; {} + batches matches into fewer invocations.
  • Always quote -name patterns so the shell doesn't expand them before find runs.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.