Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Files older than 3 years

I need to remove any file in the directory that is older than 2 years old. It is very important that I keep the newest files and delete the old files.

I have searched and found this.

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

Can I just multiply the number?

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

Is there a way to add a switch that will print the file name to the screen as it removes it? To make sure it is doing what I am expecting?

I have also found this:

find /rec -mtime +365 -print0 | xargs -0 rm -f

Is there a major difference between the two? Is one better than the other? What I have read says that xargs is faster. Would I be able to multiply the mtime number out to a 2nd or 3rd year?

And finally would would I be able to place the code as it is into a cron job that can run daily?

Thank you!

like image 957
Joshua Haws Avatar asked Feb 16 '15 04:02

Joshua Haws


2 Answers

Can I just multiply the number?

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

Yes. And to "echo" before you remove

find /path/to/files -mtime +1095 -print

Then the version with -exec rm {} \; to remove the files (when you are ready).

like image 144
Elliott Frisch Avatar answered Nov 11 '22 04:11

Elliott Frisch


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

That should work fine, you can run a dry a run of this by simply listing the files that are found by the command:

find /path/to/files* -mtime +1095 -exec ls {} \;

To be safe though I would also add in a -type to ensure that other things dont get deleted:

find /path/to/files* -type f -mtime +1095 -exec rm {} \;
like image 2
Voycey Avatar answered Nov 11 '22 02:11

Voycey