Linux Bash: how to delete old files and filter by extension

28.06.2023 Author:

Regularly removing old files helps keep a server tidy. Learn how to find files by modification time, filter by extension and check the results before deletion.

This article explains how to find and delete files older than 30 days. Here, a file’s age refers to the time since its last modification.

Deleting files older than 30 days

The find command lets you locate files based on their modification time. You can then delete matching files with a single command.

First, list files in /backup that match the 30-day age filter:

find /backup -type f -mtime +30

Review the results and make sure the list does not include files you still need. Once you have checked it, delete the matching files:

find /backup -type f -mtime +30 -delete

Deleting files with a specific extension

You can add filters instead of deleting every matching file. For example, you can select only .log files using the same modification-time filter.

First, run the command without deletion to inspect the results:

find /var/log -name "*.log" -type f -mtime +30

After reviewing the list, delete the matching files:

find /var/log -name "*.log" -type f -mtime +30 -delete

This command deletes only files with the .log extension that satisfy the modification-time filter.

Deleting old directories recursively

The -delete action cannot remove a non-empty directory. To remove a directory together with its contents, you can combine find with rm.

First, list directories under /var/log that match the 90-day modification-time filter:

find /var/log -mindepth 1 -type d -mtime +90

After checking the list, use -exec to run rm on each matching directory:

find /var/log -mindepth 1 -depth -type d -mtime +90 -exec rm -rf -- {} \;

The escaped semicolon terminates the -exec action. The -mindepth 1 option excludes the starting directory itself. A directory’s modification time does not tell you the age of every file inside it, so check its contents before deleting it recursively.

About the author

Leszek Iwaniec is the owner of Projectic. He works on online store implementations, custom applications and technical support. On the blog, he describes problems and solutions involving PrestaShop, Laravel and system integrations, drawing on the team’s project experience.

Back