Linux command to delete files or directories older than x days

So here is a bash/shell/Linux script/command that will allow you to delete any kind of directories or files that are older than x days. This is particularly useful when you are doing regular database dumps or logging, and you need to make sure you don’t fill up the hard drive space.

find /home/user/deletefromhere -type f -ctime +10 -exec rm -rf {} +

-type f (look for files) can be replaced with -type d (look for directories) or can be removed if you want to delete both files and directories.

Change +10 to any number, say +7 to delete the files older than 7 days.

Make sure you test it out first. You can find what will be deleted before running the command by removing everything including and after the -exec flag so by running:

find /home/user/deletefromhere -type f -ctime +10 will show you all the files (not directories) that will be deleted – which happens to be files older than 10 days.

Feels like I wrote too much about something that should be pretty simple, but one can never be too careful.

Any questions please leave a comment, thanks!

Comments

  • tsunkri

    March 27, 2016 at 7:47 am

    you save my day

  • Nirmal

    March 12, 2019 at 4:27 am

    Shouldn’t it be -7 for file created 7 days or earlier? same for -10?

Write a comment

Your email address will not be published. Required fields are marked *

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