How to Delete Files Older than 30 days in Linux

Channel: Linux
Abstract: list all files older than 30 days under /opt/backup directory. find /opt/backup -type f -mtime +30if the directory is not empty. In that case we will

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.

1. 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 {} \; 
WARNING: Before removing the directory, Make sure no useful directory is being deleted. Some times parent directory modification date can be older than child directories. In that case recursive delete can remove child directory as well.Conclusion

In this tutorial, you have learned to search and delete files modified older than specific days in Linux command line.

Ref From: tecadmin

Related articles