The find
command is one of Linux/Unix’s most powerful tools for hunting down files. But most users barely scratch its surface! Here’s how to leverage find
like a sysadmin ninja:
1. Basic Structure Refresher
find [starting/directory] [criteria] [action]
Example:
find /home -name "*.txt" -print
2. Powerful Search Criteria
🔍 By File Type
-type f
: Regular files-type d
: Directories-type l
: Symbolic linksfind /var -type d -name "log*" # Find directories starting with "log"
📏 By Size
-size +10M
: Files > 10MB-size -1G
: Files 30 days agofind /backup -mtime +180 -delete # Delete files older than 6 months
🔐 By Permissions
find . -perm 644 # Exact permission match
find /etc -perm -u=r # Files readable by owner
👤 By Ownership
find /var/www -user www-data # Files owned by user "www-data"
3. Combine Conditions Logically
- AND (implied):
find / -name "*.conf" -size +1M
- OR:
-o
find . \( -name "*.jpg" -o -name "*.png" \) # JPG OR PNG
- NOT:
!
find ~ ! -user $(whoami) # Files NOT owned by you
4. Execute Actions on Results
🚀 Run Commands
-exec
: Replace{}
with filename,\;
to endfind ./docs -name "*.old" -exec rm {} \; # Delete .old files
⚡ Faster Alternative
Use+
to batch process:find ./cache -name "*.tmp" -exec rm {} + # Deletes ALL in one command
💾 Preserve Structure
Copy files while keeping paths:
find src/ -name "*.java" -exec cp --parents {} /backup \;
5. Regex Power with -regex
Case-sensitive regex matching:
find . -regex ".*/backup-[0-9]{4}.tar.gz" # Matches precise backup patterns
6. Optimization Tips
- Limit Filesystem Searches:
find /mount -xdev -name "lostfile" # Restrict to one filesystem
- Depth Control:
-maxdepth 3
: Search only 3 subdirectories deep
7. Real-World Examples
🔍 Find & Archive Logs
find /var/log -name "*.log" -mtime -1 -exec tar -czf logs.tgz {} +
🧹 Clean Temp Files
find /tmp -type f -atime +2 -delete
⚠️ Detect Suspicious Files
find / -type f -perm /4000 # Find all SUID files (potential security risks)
💡 Pro Tip: Use -printf
for Custom Output
Format results like a CSV:
find . -type f -printf "%p,%s bytes,%TY-%Tm-%Td\n" > report.csv
Master these techniques, and you’ll slice through filesystem chaos with precision! 🚀 Test commands in a safe directory first—find
+ -delete
/-exec
demands respect!