How to delete files older than a certain number days in Linux


Once we have automated a VPS server backup, it is unavoidable the fact that we will have to delete older files after a certain number of days. To avoid deleting them manually (which means connecting to the server, which can become tiresome), one line can be written in one of the scripts you use for the backup.

The line is actually a find command with some advanced options:

find /mnt/directory/ -type f -mtime +4 -exec rm — {} \;


/mnt/directory/ – is obviously the path to the directory where the older n days files will be searched (replace the path to the directory you want)
-type f – the command will only apply to files
-mtime +4 – this argument is used to specify the files to be deleted (I chose to delete files older than 4 days) – mtime – refers to days
-exec – this argument allows the result of the find command to be passed to another command (rm in our case)

Similarly, we can do the following:

• find and delete modified files in the last 30 minutes (mmin refers to minutes):

find /tmp/ -type f -mmin 30 -exec rm {} \;

• force deleting files older than 30 days from a directory (for example /tmp):

find /tmp -mtime +30 -exec rm -f {} \

• move files older than 30 days and archive them, keeping the directory structure (the -t option of the mv command ensures that the directory structure is preserved):

find /tmp -mtime +30 -exec mv -t {} /archive/directory/ \;

These commands can also be put into a cron task and run in any Linux distribution.

Recent Posts