How to Find Files Older Than N Days in Linux Using the Find Command
How to Find Files Older Than N Days in Linux Using the Find Command
Find Files Older Than a Specified Number of Days in Linux
Managing old files is a common task for Linux administrators. Whether you need to clean up log files, archive backups, or identify stale data, the find command provides a simple and powerful solution.
Basic Syntax
find /directory/path -mtime +N -exec ls -lrth {} \;
Example
To find files that were last modified more than 30 days ago under /var/log:
find /var/log -mtime +30 -exec ls -lrth {} \;
Understanding the Parameters
| Parameter | Description |
|---|---|
find | Searches for files and directories. |
/var/log | Directory where the search begins. |
-mtime +30 | Finds files modified more than 30 days ago. |
-exec | Executes a command on each matched file. |
ls -lrth | Displays detailed file information in human-readable format. |
{} | Represents the matched file. |
\; | Terminates the -exec command. |
Common Use Cases
Find Files Older Than 7 Days
find /tmp -mtime +7
Find Files Older Than 90 Days and Delete Them
Use with caution.
find /backup -type f -mtime +90 -delete
Find Only Log Files Older Than 30 Days
find /var/log -name "*.log" -mtime +30
Find Files Older Than 60 Days and Compress Them
find /data/archive -type f -mtime +60 -exec gzip {} \;
Preview Before Deleting
Before removing files, it is recommended to review the results:
find /directory/path -type f -mtime +30 -exec ls -lh {} \;
This helps prevent accidental deletion of important files.
Conclusion
The Linux find command is an essential tool for file management and system maintenance. By combining -mtime with actions such as listing, compressing, or deleting files, administrators can efficiently manage disk space and automate cleanup tasks.
Quick Reference
Older than 7 days:
-mtime +7Older than 30 days:
-mtime +30Older than 90 days:
-mtime +90Delete old files:
-deleteShow file details:
-exec ls -lrth {} \;
Using these options can help keep Linux systems organized, efficient, and free from unnecessary storage consumption.