Bash find Command - Search for Files
Using the find Command
The find command searches a folder, and all folders inside it, for files and directories that match what you ask for.
You can search by name, type, size or age, and you can even run a command on every match.
All examples below use this folder:
project/
index.html
style.css
notes.txt
README.TXT
logs/
app.log
scripts/
build.sh
test.sh
Find Files by Name
Use -name followed by a pattern. The * wildcard matches any characters.
The first argument (.) tells find to start in the current folder:
Put the pattern in quotes. Without quotes, Bash may expand the * itself before find sees it.
Ignore Upper and Lower Case
The -name option is case-sensitive, so README.TXT was not found above.
Use -iname to ignore case:
Find by Type
Use -type f to find only files, and -type d to find only directories:
You can combine tests. This finds files whose name ends with .sh:
Example: Find Shell Scripts
find . -type f -name "*.sh"
./scripts/test.sh
./scripts/build.sh
Limit the Search Depth
By default, find looks inside every sub-folder. Use -maxdepth to limit how deep it goes.
-maxdepth 1 means "only the starting folder":
Example: Search Only the Current Folder
find . -maxdepth 1 -type f
./README.TXT
./notes.txt
./style.css
./index.html
Find by Size and Age
Use -size to find files bigger (+) or smaller (-) than a size. k means kilobytes, M megabytes:
Use -mtime to find files by when they were last changed, in days. -7 means "less than 7 days ago":
Run a Command on Each File
Use -exec to run a command on every file that is found. The {} is replaced by the file name, and \; ends the command:
Example: Count the Lines in Each Script
find . -name "*.sh" -exec wc -l {} \;
1 ./scripts/test.sh
1 ./scripts/build.sh
Use -delete to delete every file that is found:
Be careful: -delete removes files without asking. Run the same command without -delete first, to see which files will be removed.
Options Overview
-name: Match the file name (case-sensitive)-iname: Match the file name (ignore case)-type f/-type d: Only files / only directories-maxdepth: How many folder levels to search-size: Match by file size-mtime: Match by days since the file was last changed-exec: Run a command on each match-delete: Delete each match