Terminal · intermediate
Finding files with find
find traverses directory trees from explicit starting points and evaluates an expression of tests and actions for each encountered pathname.
Why it matters
Its expression model can select and act on files without parsing formatted directory listings, but operator precedence and destructive actions require care.
Mental model
How to reason about finding files with find
For every visited entry, evaluate the expression left to right under find's precedence rules; tests produce truth values and actions can also affect expression truth.
Analogy
It is an inspector walking every aisle from a chosen entrance, applying a checklist to each item and performing an action only when the complete rule allows it.
Examples
See the boundary, not just the happy path
Worked example · Find recent log files
find /var/log -type f -name '*.log' -mtime -7 -printThe shell quotes the pattern so find receives it literally; find then selects regular files with matching names and modification age.
Worked example · Batch a safe action
find src -type f -name '*.dart' -exec grep -lF TODO {} +-exec ... {} + passes matched pathnames as arguments in batches without converting them through newline-delimited text.
Avoid · Parsing ls output
for file in $(ls *.log); do process "$file"; doneCommand substitution and word splitting lose filename boundaries; find actions or shell globs preserve pathnames as arguments.
Common mistakes
Misconceptions to remove early
Leaving -name patterns unquoted
The shell can expand *.log before find starts, changing one intended pattern into unrelated command arguments.
Adding -delete before validating selection
Print and review the same expression first, narrow its starting point, and understand that -delete is irreversible and can imply depth-first traversal.
Quick check
Can you predict the result?
1. Why should '*.json' be quoted in find . -name '*.json'?
- • So find receives the pattern instead of the shell expanding it in the current directory.
- • So JSON files become hidden.
- • Because -name accepts only quoted strings.
2. What advantage does -exec command {} + have over parsing printed pathnames?
Keep building