Bash find Command - Advanced File Search Techniques

Master the find command for advanced file searching including combining conditions, executing commands on results, using -exec vs xargs, and practical search patterns.

File Operations

Detailed Explanation

Advanced find Command Usage

The find command is one of the most powerful tools in the Unix toolkit. Beyond basic file searching, it supports complex logical expressions, multiple actions, and integration with other commands.

Combining Conditions

# AND (implicit)
find . -name "*.js" -type f -mtime -7

# OR
find . \( -name "*.js" -o -name "*.ts" \) -type f

# NOT
find . -not -name "*.test.js" -name "*.js" -type f

# Complex logic
find . \( -name "*.js" -o -name "*.ts" \) -not -path "*/node_modules/*" -type f

Executing Commands

# -exec (runs once per file)
find . -name "*.log" -exec rm {} \;

# -exec with + (batches files, more efficient)
find . -name "*.js" -exec grep -l "TODO" {} +

# Using xargs (more flexible)
find . -name "*.tmp" -print0 | xargs -0 rm

# Confirmation before each action
find . -name "*.bak" -exec rm -i {} \;

Size-Based Searches

# Files larger than 100MB
find / -type f -size +100M

# Files smaller than 1KB
find . -type f -size -1k

# Empty files
find . -type f -empty

# Empty directories
find . -type d -empty

Time-Based Searches

# Modified in last 24 hours
find . -mtime 0

# Modified more than 30 days ago
find . -mtime +30

# Accessed in last hour
find . -amin -60

# Changed in last week
find . -ctime -7

# Modified between dates (using reference files)
find . -newer start_marker -not -newer end_marker

Permission-Based Searches

# Find world-writable files
find / -type f -perm -o+w

# Find SUID executables
find / -type f -perm -4000

# Find files NOT owned by root
find / -not -user root -type f

# Find files with specific permissions
find . -perm 755 -type f

Practical Recipes

# Delete old log files
find /var/log -name "*.log" -mtime +90 -delete

# Find duplicate files by size
find . -type f -exec md5sum {} + | sort | uniq -d -w 32

# Count files by extension
find . -type f | sed 's/.*\.//' | sort | uniq -c | sort -rn

# Find largest directories
find . -maxdepth 3 -type d -exec du -sh {} + | sort -rh | head -20

Use Case

Advanced find usage is essential for disk cleanup automation, security audits (finding world-writable files or SUID binaries), codebase maintenance (finding unused files, large binaries committed to git), log rotation scripts, and backup scripts that need to select files based on complex criteria.

Try It — Bash Cheat Sheet

Open full tool