This article will show you how to delete files older than a given number of days (or hours/minutes) manually or automatically via a Bash script. Examples included.
Removing files older than a certain number of days (or minutes, or hours) makes use of two Linux commands – rm and find.
Deleting Files with rm
First up, the rm command. The rm command is used to remove files and directories in Linux. Here’s a whole article about how it’s used:
rm Command in Linux [With Examples]
Passing a Filtered List of Files to rm
The next component, the find command. The find command is used to find files based on a set of criteria – in this case, the age of the file (time passed since it was modified). Here’s our article on the find command:
Find Command in Linux [With Useful Examples]
Putting Them Together – Example
Using find and rm together:
find /path/to/files/* -mtime +7 -exec rm {} \;
What’s happening here?
- find is called on the directory /path/to/files
- the -mtime option is passed to find with the value +7 passed to it – meaning files modified more than 7 days ago
- The exec option is passed to find with the command to run against each matching file
- rm is called by the -exec option in find
- it will remove all files matching the conditions given to find
- The curly braces, slash, and semicolon at the end of the line signal the end of the command find should run on each matching file
Hours, Minutes Instead of Days
To use minutes instead of days as the unit of time, you can substitute -mmin instead of -mtime.
find /path/to/files/* -mmin +30 -exec rm {} \;
The above example would delete files older than 30 minutes.
Making it into A Script
Rather than typing this out, you could make it into a script
#!/bin/bash find /path/to/files/* -mtime +7 -exec rm {} \;
Save the above snippet into a file (named deletescript.sh, for example), and then it can be called by running:
./deletescript.sh
You could also create an alias for the command if you want to run it from anywhere.
Scheduling Deletion of Old Files
If you want to run the command automatically at a set interval, add it to your crontab. The crontab file is where a user’s scheduled tasks are kept in Linux, and it can be edited by running:
crontab -e
On running the above, the crontab editor will be displayed. Simply append the following to the file to run the script every day:
@daily find /path/to/files/* -mtime +7 -exec rm {} \;
Many thanks!
I have a couple BASH scripts to record my ISP’s quality by logging the speed every half hour with speedtest-cli in one file and monitoring downtime with curl, nc, ping and wget in another. My log files are created either daily with cron at midnight, or if my PC isn’t running through midnight, they’re created by date when I start up. I have them in ‘Startup Applications’. Either way, that gives me two log files for each day I’m on and I needed a way to thin the herd.
This works wonderfully! And your explanation was superb!
Again, Thank You!
Glad it helped!