Linux: Delete Files Older Than X Days

This is a very simple tutorial how to find and delete files older than X days. I needed this for a project where i collected some images and after a while they took too much space.

With this you will be able with the Linux find command to find your JPG files older then 30 days and then execute rm command on them.

Delete command

find /path/to/files/ -type f -name '*.jpg' -mtime +30 -exec rm {} \;

Explanation

  • First part is the path where your files are located. Don’t use wildcard * if you have a lot of files because you will get Argument list too long error.
  • Second part -type is the file type f stands for files
  • Third part -name is limiting *,jpg files
  • Fourth part -mtime gets how many days the files older then will be listed. +30 is for files older then 30 days.
  • Fifth part -exec executes a command. In this case rm is the command, {} gets the filelist and \; closes the command

Move command

find /path/to/files/ -type f -name '*.jpg' -mtime +30 -exec mv {} /path/to/archive/ \;

Explanation

  • First part is the path where your files are located. Don’t use wildcard * if you have a lot of files because you will get Argument list too long error.
  • Second part -type is the file type f stands for files
  • Third part -name is limiting *,jpg files
  • Fourth part -mtime gets how many days the files older then will be listed. +30 is for files older then 30 days.
  • Fifth part -exec executes a command. In this case mv is the command, {} gets the filelist, path where to move the files and \; closes the command

Combine commands

Now we can combine this two command to archive the images older than 10 days and delete them from the archive folder if they are older then 30 days.

We are going to create a shell script that will do that and we can run it with a crontab.

#!/bin/bash
/usr/bin/find /path/to/files/ -type f -name '*.jpg' -mtime +10 -exec mv {} /path/to/archive/ \;
/usr/bin/find /path/to/archive/ -type f -name '*.jpg' -mtime +30 -exec rm {} \;

This command should work on most of the Linux distributions.

More on findhttp://www.linuxmanpages.com/man1/find.1.php

  • Asanokatana

    I know this page was written a few years ago, but this was incredibly helpful and easy to follow. Thank you!

  • Coverup

    I agree, very usefull post, regards

  • Coverup

    btw everything goes wrong if you type /folder instead /folder/, instead move, a file called folder is created and is just garbage, so dont forget the / at the end

  • Peter Stefanovic

    Decent page there Nikola.

    Cant stand your name though.

  • Donatello Tuttle

    Guys, I just shit myself reading this… what do I do??