Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 0 down vote accepted

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 {} \;
share|improve this answer
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. – Matt 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 1 '12 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.

share|improve this answer
like minds think alike. just as I hit save yours came up. – Matt Jan 31 '12 at 21:30
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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