find

Mastering the find command for locating files and directories using various search criteria and actions

The find command is one of Linux’s most powerful tools for locating files and directories. It recursively searches through directory trees based on various criteria like name, size, permissions, and modification time. Essential for system administration, file management, and automation tasks.

Key Concepts

  • Search Path: Starting directory for the search
  • Expression: Criteria used to match files
  • Action: What to do with matching files
  • Recursive: Searches subdirectories automatically
  • Real-time: Searches live filesystem, not a database

Command Syntax

find [path] [expression] [action]

  • path: Where to start searching (default: current dir)
  • expression: What to look for
  • action: What to do with results (default: print)

Common Options

-name pattern - Search by filename pattern -type f/d - Find files (f) or directories (d) -size [+/-]N - Find by file size -mtime N - Modified N days ago -perm mode - Find by permissions -user username - Find by owner -exec command {} \; - Execute command on results

Practical Examples

Example 1: Find by name

1
find /home -name "*.txt"

Finds all .txt files in /home directory

Example 2: Find large files

1
find / -type f -size +100M

Locates files larger than 100MB

Example 3: Find and delete

1
find /tmp -name "*.tmp" -delete

Removes all .tmp files from /tmp

Example 4: Find by modification time

1
find /var/log -mtime +30

Shows files modified more than 30 days ago

Example 5: Find by permissions

1
find /home -type f -perm 777

Finds files with 777 permissions

Use Cases

  • System cleanup: Remove old temporary files
  • Security audits: Find files with wrong permissions
  • Backup preparation: Locate files to archive
  • Troubleshooting: Find configuration files
  • Automation: Batch operations on file groups

locate - Fast filename search using database which - Find executable programs in PATH whereis - Locate binary, source, manual files grep - Search within file contents ls - List directory contents

Tips & Troubleshooting

Performance Tips

  • Start searches from specific directories, not root
  • Use -type early in expression for efficiency
  • Consider locate for simple name searches

Common Issues

  • Permission denied: Use sudo or redirect errors: find / -name "file" 2>/dev/null
  • Too many results: Add more specific criteria
  • Slow searches: Avoid searching from root (/)

Security Notes

  • Be careful with -exec and -delete actions
  • Test expressions before adding destructive actions
  • Use -print first to verify results

Useful Combinations

1
2
3
4
5
6
7
8
# Find and change permissions
find /var/www -type f -exec chmod 644 {} \;

# Find empty files
find /home -type f -empty

# Find recently modified files
find /etc -mmin -60