Quantcast
Channel: Linux Guides, Tips and Tutorials | LinuxScrew
Viewing all articles
Browse latest Browse all 314

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

$
0
0

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 {} \;

View the original article from LinuxScrew here: Delete Files Older Than X Days/Hours in Bash [Examples]


Viewing all articles
Browse latest Browse all 314

Trending Articles