Delete files older than

Last Updated on 2022-07-08 by Joop Beris

It is just one of those things that as an admin, you sometimes come across. There’s a directory somewhere that fills up with clutter. Every day, programs dump temporary files there or users upload stuff and before long, there are thousands of files of debris and cruft. How do you keep this directory neat and tidy? Easy, you just make a small script that will delete files older than x days.

On Linux, you can easily search for files to delete using the find command. Let’s say you want to keep all files for a week and then get rid of them. Here’s how you find all files that are older than 7 days.

$ find /path/to/files -mtime +7 -type f

This command finds all ordinary files in the specified directory that were modified more than 7 days ago. Why modified and not created? Easy: this ensures you delete files that really haven’t been touched in the last 7 days.
If you run the above command, you’ll probably get a listing of files. If this list seems correct, you can remove those files by expanding the command above just a little.

$ find /path/to/files -mtime + 7 -type f -exec rm {} \;

The above command list all the ordinary files in the specified directory that were modified more than 7 days ago and then runs the command rm (remove) against them. Depending on how many matching files there are in this directory, this command can take a while.

Sticking the above command in a simple shell script, you can schedule it via cron and presto, that cluttered directory will be automatically cut to size without you having to worry about it.

0 0 votes
Rate this article

If you liked this article, you might enjoy these too:


Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Let me know your thoughts on this post. Leave a comment, please!x
()
x