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?

3 Answers 3


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 {} \;
  • 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, 2012 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 1, 2012 at 18:04

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.

  • 1
    like minds think alike. just as I hit save yours came up.
    – hookenz
    Jan 31, 2012 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, 2012 at 21:36

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .