Automated log cleanup and backup rotation scripts on Linux frequently rely on GNU find to locate and delete files older than a retention threshold. Evaluating file age predicates (-mtime or -mmin) and restricting the search to regular files (-type f) prevents accidental deletion of active files or directories.
Step 1: Always Preview Matched Files First (Dry Run)
Before running any destructive removal command, list the exact files that match your criteria by running find with -print or -ls:
find /path/to/backups -type f -mtime +5 -print
Step 2: Delete Files Older Than N Days
Method 1: Using -exec rm
# Spawns one rm process per file (\;)
find /path/to/backups -type f -mtime +5 -exec rm -f {} \;
# Faster batch variant: passes multiple filenames per rm invocation (+)
find /path/to/backups -type f -mtime +5 -exec rm -f {} +
(Note the required space between {} and \; or +.)
Method 2: Using GNU find Built-in -delete Action
On Linux systems with GNU find, the -delete action removes matched files directly without forking an external rm process. Always place -delete at the very end of the find expression (since find evaluates predicates from left to right, placing -delete first would delete everything before checking -mtime!):
find /path/to/backups -type f -name "*.gz" -mtime +5 -delete
Understanding How find Calculates File Age (-mtime vs. -mmin)
| Predicate | Meaning |
|---|---|
-mtime +5 |
Modified strictly more than 5 × 24 hours ago (fractional days are rounded down, so +5 matches files at least 6 days / 144 hours old). |
-mtime 5 |
Modified between 5 × 24 and 6 × 24 hours ago. |
-mtime -5 |
Modified less than 5 × 24 hours ago (within the last 5 days). |
-mmin +360 |
Modified more than 360 minutes (6 hours) ago. |
-atime +n |
Last accessed (read) more than n days ago. |
-ctime +n |
Inode metadata (permissions, ownership, link count) last changed more than n days ago. |
Useful Safety Filters
- Restrict to regular files only (
-type f): Preventsfindfrom attempting to remove directories ("."or subdirectories). - Do not descend into subdirectories (
-maxdepth 1):find /var/log/myapp -maxdepth 1 -type f -name "*.log" -mtime +7 -delete - Delete empty directories left behind after file cleanup (
-type d -empty):find /path/to/backups -mindepth 1 -type d -empty -delete