Often you may want to use Bash to delete all files in a particular directory that are older than X hours.
You can use the following syntax to do so:
find c:/users/bobbi/data2 -type f -mmin +120 -delete
This particular example deletes all files in the data2 folder at the location we specified that are older than 2 hours (120 minutes).
Here is what the various commands do:
- find c:/users/bobbit/data2 -type f: Match all files in this location
- -mmin +120: Match files that have a modification time older than 120 minutes
- -delete: Delete the matched files
The following example shows how to use this syntax in practice.
Example: How to Delete Files Older Than X Hours in Bash
Suppose that we would like to delete all files in the folder located at c:/users/bobbi/data2 that have been modified more than 2 hours ago.
We can first use the ls command with the following syntax to first view all of the files in this folder along with their last modified times:
ls c:/users/bobbi/data2 -l
The following screenshot shows how to use this syntax in practice:

This article is currently being written on 7/30/2024 at 1PM.
We can use the following syntax to delete all files in this directory that have been modified more than 2 hours ago:
find c:/users/bobbi/data2 -type f -mmin +120 -delete
The following screenshot shows how to use this syntax in practice:

Notice that when we use the ls command again to view the updated files in the folder we can see that all files that were modified more than 2 hours ago have been deleted.
Feel free to change -mmin + 120 to a different number to instead delete files that were modified longer than a different number of hours ago.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Find All Files that Were Created Today
Bash: How to Find Files that Have Been Changed in Last 24 Hours
Bash: How to Add Prefix to All Files in Directory
