In this guide, we’ll look at how to Delete files older than n days in Linux. The most common use case for this is deleting rotated logs which are older than a certain number of days or removing old backups to clear space for more recent backups.

So let’s consider an example. I’ll search for files under /var/log with an extension of .tar.gz older than 7 days and delete them. I’ll use find command to search for the files.

# find /var/log/ -name *.gz -mtime +7 -exec rm -rf {} \;

-mtime option is used to specify last modification of file; i.e  n*24 hours ago. +7 means older than 7 days.

-exec option is used to execute a command in find. The command being executed here is rm -f

The last {} \; means loop through the list of items.

If you want to list the files without deleting them, use the command:

# cd /var/log
# find . -type f -mtime +7d -ls

To find and delete files bigger than a specified size and older than n number of days, use -size option: For example:

# find /var/log/ -name *.gz -mtime +7  -size +1G -exec rm -rf {} \;

Note that it is possible to save the list of files into a variable before deleting them.

# file_list=`find . -name *.gz -type f -mtime +7`
# for i in ${file_list[@]}; do
  echo "Deleting $i file"
  rm $i

For more find options, refer to its man page:

# man find

Your support is our everlasting motivation,
that cup of coffee is what keeps us going!

As we continue to grow, we would wish to reach and impact more people who visit and take advantage of the guides we have on our blog. This is a big task for us and we are so far extremely grateful for the kind people who have shown amazing support for our work over the time we have been online.

Thank You for your support as we work to give you the best of guides and articles. Click below to buy us a coffee.


Please enter your comment!
Please enter your name here