1

We're using an AIX server to house thousands and thousands of little files in a nested directory structure. I'm trying to write a script that will recursively delete old files, and then delete the containing directory if that was the last file in the directory.

For the purposes of examples, let's say any file older than 60 days is "old."

It sounds simple and easy, but I have looked around for a while and can't find a solution. Is there some combination of find and its flags, maybe pipelined with rmdir that will accomplish the above?

JeffK
  • 113
  • 1
  • 6

3 Answers3

2

if you define "older than" by having a modification time of more than 60 days, the following command will delete your old files:

find /your/dir -mtime +60 -exec rm -f {} \;

for pruning empty directories you could use this command:

find /your/dir -type d -exec rmdir {} \;

it doesn't exactly find empty directories, but since rmdir does not delete directories containing files, it will only delete the empty ones.

Niko S P
  • 1,182
  • 8
  • 16
  • 1
    like minds think alike. just as I hit save yours came up. – hookenz Jan 31 '12 at 21:30
  • 1
    You probably want to add a `-depth` to the line that does rmdir. That way an empty directory that contains only an empty directories would be removed. – Zoredache Jan 31 '12 at 21:36
1

I think you can combine these two commands into one:

find /your/dir -type f -mtime +60 -delete -or -type d -empty -delete

Note: -delete implies -depth.

Uwe Keim
  • 2,420
  • 5
  • 30
  • 47
Paul Dubuc
  • 13
  • 2
0

You've said you're on AIX. I think the basic shell commands will do the trick if I'm not wrong.

find /path/to/files* -mtime +60 -exec rm {} \;
find /path/to/files -type d -exec rmdir 2>/dev/null {} \;
hookenz
  • 14,472
  • 23
  • 88
  • 143
  • I think a shell script might be better (it's been too long since I wrote shell script) as it wouldn't scan the directory tree twice like the above commands are doing. – hookenz Jan 31 '12 at 21:32
  • Hard to choose "the answer" between two nealry identical solutions, but I'll pick this one because it doesn't show the _expected_ errors when it tries to delete the directories that still have files in them. I do have a concern that this will also hide any other _unexpected_ errors that may occur, so I'll probably redirect to somewhere other than /dev/null and run a grep to find any lines that don't end with " is not empty." – JeffK Feb 01 '12 at 18:04