How to Delete Files Older than 30 days in Linux

This is the best practice to remove old unused files from your server. For example, if we are running daily/hourly backup of files or database on the server then there will be much junk created on the server. So clean it regularly. To do it you can find older files from the backup directory and clean them.

This article describe you to how to find and delete files older than 30 days. Here 30 days older means the last modification date is before 30 days.

Delete Files older Than 30 Days

You can use the find command to search all files modified older than X days. And also delete them if required in single command.

First of all, list all files older than 30 days under /opt/backup directory.

find /opt/backup -type f -mtime +30 

Verify the file list and make sure no useful file is listed in above command. Once confirmed, you are good to go to delete those files with following command.

find /opt/backup -type f -mtime +30 -delete 

2. Delete Files with Specific Extension

Instead of deleting all files, you can also add more filters to find command. For example, you only need to delete files with “.log” extension and modified before 30 days.

For the safe side, first do a dry run and list files matching the criteria.

find /var/log -name "*.log" -type f -mtime +30 

Once the list is verified, delete those file by running the following command:

find /var/log -name "*.log" -type f -mtime +30 -delete 

Above command will delete only files having .log extension and last modification date is older than 30 days.

3. Delete Old Directory Recursively

Using the -delete option may fail, if the directory is not empty. In that case we will use Linux rm command with find command.

The below command will search all directories modified before 90 days under the /var/log directory.

find /var/log -type d -mtime +90 

Here we can execute the rm command using -exec command line option. Find command output will be send to rm command as input.

find /var/log -type d -mtime +30 -exec rm -rf {} \; 
  • 0 Users Found This Useful
Was this answer helpful?

Related Articles

How To: Back Up MySQL Databases From The Command Line

While automated backups are important, sometimes you just want to take a quick and dirty snapshot...

How To Install MariaDB on CentOS 6

MariaDB is a drop-in replacement for MySQL. It is easy to install, offers many speed and...

How to Display (List) All Jobs in Cron / Crontab

View Root’s Cron Jobs crontab -l  View a User’s Cron Jobs crontab -u username -l Example with...

How To: Automate Server Scripts With Cron

Servers can automatically perform tasks that you would otherwise have to perform yourself, such...

How to find sending spam emails and enable mail header in php.ini

- In Linux servers if there are a lot of emails in the queue "over 100" emails. you can check if...