Skip to content

    Find Command Mastery

    Locate files and run actions on them.

    Quick recipes

    # Find large files (> 500MB)
    find . -type f -size +500M -printf '%s %p\n' | sort -nr | head -20
    
    # Prune heavy dirs and search text
    find . -type d \( -name node_modules -o -name .git \) -prune -o \
      -type f -name '*.log' -print0 | xargs -0 grep -n "ERROR"
    
    # Delete old files (dry-run then execute)
    find /var/tmp -type f -mtime +14 -print
    # then
    find /var/tmp -type f -mtime +14 -delete

    Production checklist

    • Use -print0 and xargs -0 for NUL-safe pipelines.
    • Prefer two-step delete (print then delete), or -ok interactive.
    • Limit scope with -maxdepth, -name globs, and -prune.

    Find and Delete Old Files

    Delete files older than a cutoff in one step; common for log rotation after you have verified the matching set.

    DANGER: This command permanently deletes files! Always test without -delete first. Double-check the path and time criteria. Consider backing up important data.
    find /var/log -type f -mtime +30 -delete

    Safety tip: Test first without -delete! Run find /var/log -type f -mtime +30 to see what will be deleted

    Find Files by Size

    List files above or below a size threshold to find disk usage hotspots.

    # Find files larger than 100MB
    find /home -type f -size +100M
    
    # Find files smaller than 1MB
    find /tmp -type f -size -1M

    Size units: Use k (kilobytes), M (megabytes), or G (gigabytes)

    Find and Execute Commands

    Run a command per matched file; example compresses log files older than 7 days.

    Warning: The -exec option can modify or delete files. Always test with a safe command first (like ls or echo) before using destructive operations.
    find /var/log -type f -name '*.log' -mtime +7 -exec gzip {} \;

    Tip: Use {} as placeholder for filename. \; ends the exec command. For better performance, use + instead of \;

    Find Empty Directories

    List empty directories, optionally delete them after review.

    Warning: The -delete option permanently removes directories. Always list first to verify what will be deleted, especially in important project directories.
    # List empty directories
    find /home/user/projects -type d -empty
    
    # Delete empty directories
    find /tmp -type d -empty -delete

    Use case: Post-build cleanup or pruning empty dirs.

    Find Recently Modified Files

    Files modified within a recent time window (minutes or days).

    # Files modified in last 60 minutes
    find /etc -type f -mmin -60
    
    # Files modified in last 24 hours
    find /var/www -type f -mtime -1

    Time options: -mmin for minutes, -mtime for days. Use - for "less than", + for "more than"