Sometimes in Linux, you want to clear out older files in a directory. One instance would be if you have a security system and it continuously writes video files to a directory on your NAS (Network Attached Storage) until it fills it up. You’ve figured out that if you keep a week’s worth of video, it will usually leave plenty of space for other users.
What I would suggest here is creating a cron job that runs every night and runs something like the following command:
1 |
find /path/to/files/ -type f -mtime +7 -exec rm -rf {} \; |
What it all means:
find: the command that will search for the files
/path/to/files/: the top level directory to start searching
-type f: so we don’t remove directories, only files
-mtime +7: files older than ‘7’ days. Change to ‘+14’ to delete files older than 2 weeks.
-exec: what to do with the files we find
rm -rf: remove them recursively, force
{}: this represents each file we find
\;: the end of the exec
SO – the crontab entry would be this:
1 |
0 2 * * * /bin/find /path/to/files/ -type f -mtime +7 -exec rm -rf {} \; |
This will run every night at 2am.
Finally….I can free up so much space from my Linux now. I’m relatively new to Linux so 90% of the time I have no idea what I’m doing haha. Thanks for posting this.
Wow this is a great use of the cron job. I’m definitely keeping this command because it’d be great for any type of server that keeps old files or constant backups. For example a Minecraft server that does backups every hour. Then you could have it delete all saves older than few days or a week. Not to mention how useful this could be for managing all sorts of backups. Bookmarked for sure.
Thanks so much for posting this,
It has helped me out so much,
I’ve freed up so much space thanks to you.
Eoin
This looks incredibly useful! I’ve wanted to be able to do something like this before, but I didn’t realize it was actually possible. I should’ve realized it was. Linux is awesome like that.
I like the fact that you explained each entry in the command so that anyone can modify accordingly.
Thanks