How can I delete all files that are older than one year from a certain directory within the bash?

Thanks!

link|improve this question
feedback

4 Answers

up vote 7 down vote accepted
find /u1/database/prod/arch -type f -mtime +3 -exec rm {} \;

vi samefilename 
#!/bin/bash

find /u1/database/prod/arch -type f -mtime +3 -exec rm {} \;

The only 2 commands used are find and rm.

Find looks for files (-type f), this to exclude directories, that are older then 3 days (-mtime +3). All it finds is given to rm (-exec rm {} \; ).

You could also place the rm statement outside of find, which is supposed to be faster:

find /u1/database/prod/arch -type f -mtime +3 | xargs rm

link|improve this answer
3  
You can use + instead of \; with find for perfomance similar to xargs. – Dennis Williamson Jul 26 '10 at 14:07
2  
Also, when using xargs, please do it as find … -print0 | xargs -0 … (if available) so that pathnames with spaces (and even embedded line feed characters) are handled correctly. – Chris Johnsen Jul 26 '10 at 15:48
that is very good suggestion fro me thanks ton!! – Rajat Jul 26 '10 at 15:51
feedback

another approach I found. nice for specific dates.

touch --date="2010-1-1" x
find -not -newer x|xargs rm
link|improve this answer
feedback

tmpwatch does a good job, example:

/usr/sbin/tmpwatch $[24*365] /tmp 

Exerpt from manual:

tmpwatch recursively removes files which haven’t been accessed for a given number of hours. Normally, it’s used to clean up directories which are used for temporary holding space such as /tmp.

tmpwatch [-u|-m|-c] [-MUadfqstvx] [--verbose] [--force] [--all]
                  [--nodirs] [--nosymlinks] [--test] [--fuser] [--quiet]
                  [--atime|--mtime|--ctime] [--dirmtime] [--exclude <path>]
                  [--exclude-user <user>] <hours> <dirs>
link|improve this answer
feedback

tmpwatcher or "tmpreaper" in ubuntu.

http://linux.about.com/library/cmd/blcmdl8_tmpwatch.htm

use with -c

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.