Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Removing files & directories older than # days

Status
Not open for further replies.

vbMonk

MIS
Jun 20, 2003
19
US
I need to delete files and the directories that contain them when they, the files (and directories; they'll be of the same date), are older than a specified number of days.

I'm using the following code...

#!/usr/bin/perl -w
# cleandumps.ps -clean pgsql dump files older than 7 days
use File::Find qw(finddepth);
*name = *File::Find::name;
finddepth \&cleanfiles, "/var/lib/pgsql/backups/daily/";
sub cleanfiles{
if(-M > 6){
if(!-l && -d _){
print "rmdir $name\n";
#rmdir($name) or warn "couldn't rmdir $name: $!";
} else {
print "unlink $name\n";
#unlink($name) or warn "couldn't unlink $name: $!";
}
}
}

...and it works up to a point. If I just print the results, it shows everything exactly as I need, but if I actually perform the unlink operation, it changes the date on the directory that contains the files. At that point, the directory no longer meets the age requirement and doesn't get cleaned up. Anyone have an idea of how I can perform this kind of recursive deletion based on age?
 
push the filenames onto an array when you find them, and then act on the array to unlink the files

--Paul

It's important in life to always strike a happy medium, so if you see someone with a crystal ball, and a smile on their face ...
 
on *nix?

then
Code:
cd dir
find . -mtime +7 -exec rm -r {} \;

As you say, this assumes if a directory is >=7, all its files should go

PERL might be (probably un-measurably) faster
 
It's Linux Redhat 9 server.

Thanks for your responses. I was actually trying to write a perl script to do this because my attempt to use the find -exec in cron failed. I just figured out this morning it was because I was using two slashes before the semi-colon. That works on AIX. Apparently this Linux only wants one slash, however. I changed that and it works. So, the need for the script is gone.

Again, thanks to you who responded.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top