How to Use the Find Command in Linux: Syntax and Examples
The
find command in Linux searches for files and directories based on conditions like name, type, size, or modification time. You run it with a starting directory and options, for example, find /home -name '*.txt' finds all text files in /home and its subfolders.Syntax
The basic syntax of the find command is:
find [path] [options] [expression]
path: Where to start searching (e.g., /, . for current directory).
options: Control how find works (e.g., -type to specify file type).
expression: Conditions to match files (e.g., -name to match file names).
bash
find [path] [options] [expression]
Example
This example finds all files ending with .log in the current directory and its subdirectories:
bash
find . -type f -name '*.log'
Output
./system.log
./app/error.log
Common Pitfalls
Common mistakes include:
- Not quoting patterns with wildcards, causing shell expansion before find runs.
- Using incorrect paths or forgetting to specify a path, which defaults to current directory.
- Confusing
-name(case-sensitive) with-iname(case-insensitive).
Example of wrong and right usage:
bash
# Wrong: shell expands *.txt before find runs
find . -name *.txt
# Right: quotes prevent shell expansion
find . -name '*.txt'Quick Reference
| Option | Description | Example |
|---|---|---|
| -name 'pattern' | Find files matching name pattern | find . -name '*.txt' |
| -type [f|d] | Find files (f) or directories (d) | find /tmp -type d |
| -size [+/-]N[c] | Find files larger (+) or smaller (-) than N blocks (default) or bytes if 'c' is used | find . -size +100k |
| -mtime [+/-]N | Find files modified N days ago | find . -mtime -7 |
| -iname 'pattern' | Case-insensitive name match | find . -iname '*.jpg' |
| -exec command {} \; | Run command on each found file | find . -name '*.sh' -exec chmod +x {} \; |
Key Takeaways
Use
find with a starting path and conditions to locate files or directories.Always quote patterns with wildcards to avoid shell expansion errors.
Use
-type to specify file or directory searches.Combine
-exec to run commands on found files.Remember
-name is case-sensitive; use -iname for case-insensitive matching.