find Command Basics
In this page:
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
#!/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
Login to try C/C++/Java/PHP code in the editor
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
#!/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
Login to try C/C++/Java/PHP code in the editor
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
#!/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
Login to try C/C++/Java/PHP code in the editor
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
#!/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
Login to try C/C++/Java/PHP code in the editor
- Forgetting
findsearches recursively into subdirectories by default, which can be slower or broader than expected on large trees. - Not quoting the
-namepattern, letting the shell expand it as a glob beforefindeven sees it. - Using
find ... -exec cmd {} \;without realizing it runscmdonce per file, which is slower than-exec cmd {} +for large result sets.
find dir -name patternsearches recursively for names matching a quoted glob pattern.-type frestricts results to regular files,-type dto directories.find ... -exec cmd {} \;runs a command once per matched file;{} +batches matches into fewer invocations.- Always quote
-namepatterns so the shell doesn't expand them beforefindruns.
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: