Searching with find

find locates files anywhere in the tree by name, type, size, age and more.

Syntaxfind [path] [conditions] [action]

find walks through a directory tree looking for files that match conditions you specify. The first argument is where to start searching.

Common conditions

  • -name '*.log' — match by name (quote the pattern).
  • -type f or -type d — only files, or only directories.
  • -size +10M — larger than 10 megabytes.
  • -mtime -7 — modified in the last 7 days.

Acting on results

Add -delete to remove matches, or -exec to run a command on each one ({} stands for the found file).

Example

Example · bash
# Find every .log file under /var
find /var -name '*.log'

# Find directories called 'node_modules'
find . -type d -name node_modules

# Find files bigger than 100 MB
find / -type f -size +100M

# Delete .tmp files older than 30 days
find /tmp -name '*.tmp' -mtime +30 -delete

When to use it

  • A security team uses 'find / -perm -4000 -type f' to locate all SUID binaries on a server during a security audit.
  • A developer runs 'find . -name "*.test.js"' to list all test files before running the test suite.
  • A sysadmin uses 'find /var/log -mtime +30 -delete' to automatically remove log files older than 30 days.

More examples

Find files by name and type

Uses -name for glob matching and -type f/d to restrict results to files or directories.

Example · bash
# Find all .conf files under /etc
find /etc -name '*.conf' -type f

# Find directories named 'logs'
find /var -name 'logs' -type d

Find by size and modification time

Filters by -size and -mtime to locate large files or recently changed files across a directory tree.

Example · bash
# Files larger than 100 MB
find /var/log -size +100M -type f

# Files modified in the last 24 hours
find /home -mtime -1 -type f

Execute a command on found files

Chains -exec to run a command on every match, and uses -delete for safe, direct deletion.

Example · bash
# Print details for each .log file found
find /var/log -name '*.log' -type f -exec ls -lh {} \;

# Delete all .tmp files safely
find /tmp -maxdepth 1 -name '*.tmp' -delete

Discussion

  • Be the first to comment on this lesson.