Tag Archive for Bash

Deleting files older than x days

I cur­rently have one pro­duc­tion machine and one backup machine, and every night I use rsync to backup the impor­tant files to my backup server. The direc­to­ries are get­ting a bit messy, so I needed to delete old archive files from the direc­to­ries that I store the back­ups in. A really neat and sim­ple way to do this is as follows:

find /path/to/backups/ –type f –mtime +30 –exec rm {} \;

The type para­me­ter is telling it to find reg­u­lar files. From the man page of find:

–type c
File is of type c:
b      block (buffered) special
c      char­ac­ter (unbuffered) special
d      directory
p      named pipe (FIFO)
f      reg­u­lar file
l      sym­bolic link; this is never true if the –L option or the –fol­low option is in effect, unless the sym­bolic link is bro­ken.  If you want to
search for sym­bolic links when –L is in effect, use –xtype.
s      socket
D      door (Solaris)

mtime is check­ing when the last file was mod­i­fied, and select­ing it if it is 30 days or older.
Every­thing it finds is given to –exec rm {}. The “\;” at the end lets find know where the end of the exec com­mand is.