Delete .tmp files older than 7 days
Problem statement
A CI runner's disk keeps filling up with stale temp files. Delete every regular file under build/ whose name ends in .tmp and that was last modified more than 7 days ago. Other files, and recent .tmp files, must be kept. The tree can be recreated with:
mkdir -p build/cachetouch -d '10 days ago' build/a.tmp build/cache/b.tmptouch -d '2 days ago' build/c.tmptouch -d '30 days ago' build/report.logtouch build/cache/d.tmpExamples
Example 1
Input: Dry run first: `find build -type f -name '*.tmp' -mtime +7 | sort`
Output: build/a.tmp
build/cache/b.tmp
Example 2
Input: Run the delete command, then `find build -type f | sort`.
Output: build/c.tmp
build/cache/d.tmp
build/report.log
Explanation: report.log is old but not a .tmp file; c.tmp and d.tmp are recent.
Hints
Approach
Optimal
find build walks the tree. -type f limits it to regular files so a directory named x.tmp is never touched. -name '*.tmp' matches the file name; the quotes stop the shell from expanding *.tmp in the current directory before find sees it. -mtime +7 means modified more than 7 full 24-hour periods ago. -delete removes each match. Tests are evaluated left to right, so -delete must come last, after all the filters.
find build -type f -name '*.tmp' -mtime +7 -deleteFollow-up questions
- How would you schedule this nightly and log what was deleted? (cron,
-print -delete >> log) - How is this different from
find ... -exec rm {} \;and-exec rm {} +?
Frequently asked questions
find divides the file age by 24 hours and drops the fraction, then +7 means 'more than 7', so a file needs to be at least 8 full days old. A file 7.5 days old has age 7 and is kept. Use -mmin +10080 if you need minute precision.
find evaluates its expression left to right and -delete is an action that always runs when reached. find build -delete -name '*.tmp' deletes everything under build before the name test is ever checked. Always put filters first and do a dry run with -print.