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 done
For more find options, refer to its man page:
# man find