How to Delete Files Older Than X Number of Days in Linux

After reading our old article on Linux Backup, many readers asking how to keep limited amount of backup files or how to delete backup files older than x number of days so now I am writing this guide in response to our readers question,


Queries from the readers:

How to delete backups that are older

How do i keep only limited amount of these backup files


Using find utility we can easily figure out files older than x number of days and then use the rm command to delete them.
Here is combination of find and rm command to find and delete older files using some interesting arguments.

1- Find All Files Inside Directory and Delete Files which is Older Than 10 Days

find /location/to/find/files/* -mtime +10 -exec rm {} \;

Command Explanation:

1- find /location/to/find/files/*

This command use to find files in Linux operating system. Next part of this command is /locatin/to/find/files/ which means find files inside this directory suppose I have directory on root named backup so my command will be find /backup/*.

2- mtime +10

The next argument -mtime, is used to specify the number of days. In our example we uses -mtime +10 so it will find files older than 10 days.

3- -exec rm {} \;

The last argument contains two parts, “–exec” allows you to pass an other command such as rm, and the second part “{} \;” is required to end the command.

2- Delete Files which is Older Than 5 Days With .tar File Extension.

find /backup -name "*.tar" -type f -mtime +5 -exec rm -fr {} \;

Very Important: Be VERY careful to supply an absolute path while using “rm” commands!.

3- Find and Delete Files using Find Command.

Same task you can perform using find command only. See below example:

find /location/to/find/files/* -mtime +10 -type f -delete

Tip:- you can add this command in bash script and automate this process using cron job utility.

Similar Posts