How to Find and Delete Files Older than 30 days in Linux

The best practice is to remove old and unused files from your server. For example,suppose we have lots of scheduled jobs running on regular basis which create lots of log files on particular interval continuously which keep filling space on server. So it is always recommended to clean it regularly. To do it you can find older files from these directories and clean them as per your requirement. This post will guide you to find and delete files older than 30 days.

1. Delete Files Older Than 30 Days

It’s always a best practise to test the commands before running it on server.Let me explain you the syntax of the command in general.

find sourcedirectory -type f -mtime +day -exec operation {} \;

Where

find – Command to find something.

f – donotes File type

day – No, of days.

operation – such as ls,rm etc.

The below command will delete all files older than 30 days in system /user/home/ directory but before deleting the file make sure that you are deleting the right file to check the same you can run ls -ltr instead of rm -f.

To list all the files Older Than 30 Days.

find /user/home/ -type f -mtime +30 -exec ls -ltr {} \;

The above command list of all the files which are older then 3o days and to delete all files older than 30 days in system you can use below command.

To delete all the files Older Than 30 Days.

find /user/home/ -type f -mtime +30 -exec rm -f {} \;

2. Delete Files Older Than 30 Days with .log Extension

If you want to list and delete the files with specific extension , you can use the following command.

 

To list the files with specific extension Older Than 30 Days.

find /user/home/log -name “*.log” -type f -mtime +30 -exec ls -ltr {} \;

To delete the files with specific extension Older Than 30 Days.

find /user/home/log -name “*.log” -type f -mtime +30 -exec rm -f {} \;

Similary you can list and delete files older then 7 day or 1 year what all you to replace is the no. of days from the command.

To delete all the files Older Than 7 Days.

find /user/home/ -type f -mtime +7 -exec ls -ltr {} \;

To delete all the files Older Than 1 year.

find /user/home/ -type f -mtime +365 -exec ls -ltr {} \;

30 Basic UNIX Commands List With Examples

Hope the above command is clear to you and if you have any query, you can comment in the comment box.