Sometimes it can be helpful to delete files over a certain age from a directory. For example, you may want to remove all mail files in a “Trash” folder older than 90 days, or all files in the Samba Recycle Bin that are older than 30 days.
Test Environment
When it comes to automatically deleting files, it makes sense to carry out the initial configuration in a test environment.
Let’s start by creating 50 files dated yesterday, the day before, and so on for 50 days:
mkdir /tmp/mytestdir cd /tmp/mytestdir for a in $(seq 50); do touch ${a}.txt --date="$a days ago"; done ls -lrt
You should see that you have 50 files in that directory, dated one per day over the last fifty days. They are what we will use to test the commands on this page.
Find The Files To Delete
We can use the find
command to select files according to various criteria. Let’s start by listing all files over 40 days old:
find /tmp/mytestdir -mtime +40 /tmp/mytestdir/50.txt /tmp/mytestdir/49.txt /tmp/mytestdir/48.txt /tmp/mytestdir/47.txt /tmp/mytestdir/46.txt /tmp/mytestdir/45.txt /tmp/mytestdir/44.txt /tmp/mytestdir/43.txt /tmp/mytestdir/42.txt /tmp/mytestdir/41.txt
Deleting The Files
The command above shows how to select files based on their last-modified date. Once we’ve checked which files will be selected, we can delete them:
find /tmp/mytestdir -mtime +40 -delete
This is the same find command as before, but with -delete
appended. As you might expect, this deletes the files that match the selection criteria.
How It Works
The first argument to the find command, /tmp/mytestdir
, specifies the starting point: by default, only files in or below this directory will be acted upon.
The second argument, -mtime
, is used to specify the “last modified” age in days of the files to search for. +40
specifies files last modified more than 40 days ago; similarly, -3
would specify files last modified less than three days ago.
The third argument, -delete
, deletes all the files that match the selection criteria.
Use In Production
Once you’re happy that the command works as intended, it can be wrapped in a shell script and perhaps dropped into /etc/cron.daily
so that it runs every night.
Could this Linux Tip be improved? Let us know in the comments below.