Delete Files Older Than X Days/Hours in Bash [Examples]

Bash Deleting Files Older Than X

This article will show you how to delete files older than a given number of days (or hours/minutes) manually or automatically via a Bash script. Examples included.

Removing files older than a certain number of days (or minutes, or hours) makes use of two Linux commands – rm and find.

Deleting Files with rm

First up, the rm command. The rm command is used to remove files and directories in Linux. Here’s a whole article about how it’s used:

rm Command in Linux [With Examples]

Passing a Filtered List of Files to rm

The next component, the find command. The find command is used to find files based on a set of criteria – in this case, the age of the file (time passed since it was modified). Here’s our article on the find command:

Find Command in Linux [With Useful Examples]

Putting Them Together – Example

Using find and rm together:

find /path/to/files/* -mtime +7 -exec rm {} \;

What’s happening here?

  • find is called on the directory /path/to/files
    • the -mtime option is passed to find with the value +7 passed to it – meaning files modified more than 7 days ago
    • The exec option is passed to find with the command to run against each matching file
  • rm is called by the -exec option in find
    • it will remove all files matching the conditions given to find
    • The curly braces, slash, and semicolon at the end of the line signal the end of the command find should run on each matching file

Hours, Minutes Instead of Days

To use minutes instead of days as the unit of time, you can substitute -mmin instead of -mtime.

find /path/to/files/* -mmin +30 -exec rm {} \;

The above example would delete files older than 30 minutes.

Making it into A Script

Rather than typing this out, you could make it into a script

#!/bin/bash

find /path/to/files/* -mtime +7 -exec rm {} \;

Save the above snippet into a file (named deletescript.sh, for example), and then it can be called by running:

./deletescript.sh

You could also create an alias for the command if you want to run it from anywhere.

Scheduling Deletion of Old Files

If you want to run the command automatically at a set interval, add it to your crontab. The crontab file is where a user’s scheduled tasks are kept in Linux, and it can be edited by running:

crontab -e

On running the above, the crontab editor will be displayed. Simply append the following to the file to run the script every day:

@daily find /path/to/files/* -mtime +7 -exec rm {} \;
SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *