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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

I need to delete directories that are older than six months

Status
Not open for further replies.

ariell

Programmer
Jul 3, 2002
12
US
I am using AIX and need to create a script that deletes sub directories under a directory. These sub-directories are over a year an a half old or more. I need to keep only five months and need it to run monthly to only keep five months from this point. I have tried the -mtime commands, and nothing seems to really work with deleting directories. Anyone with any suggestions?
 
I'm more used to Solaris, but the "find" command should be the same on both. Your "find" command string should look something like this:

find <dirname> -type d -mtime -180 -exec rm -rf {} \;

This will find all directories older than 180 days old and delete the directories and their contents. This is safe enough if you're sure you won't need the directories themselves again. Otherwise, you might want to substitute the &quot;type d&quot; with &quot;type f&quot;, so that only the files are removed.
 
Oh, yes, I forgot -- if you want this to run every month at the same time, then you should set up a crontab entry for the user that should be running this, something like the following;

0 1 1 * * find <dirname> -type d -mtime -180 -exec rm -rf {} \;

This will run the &quot;find&quot; command on the first day of every month at 1:00AM. The &quot;find&quot; will search in dirname for any directories older than 180 days old and delete those directories and their contents. Remember, the user that runs this needs to rwx privileges in dirname.
 
When deleting directories, don't forget to include the -prune directive to the find command. That way when you delete the directory you won't get the error message can't find &quot;directory/subdir/subsubdir&quot;.

I would first try:
Code:
find <directory> -type d -mtime +180 -prune -print
to make sure you will affect only the directories that you want deleted. If you are confident then, do the find command with the -exec rm -rf {} \; at the end. That is the part that does the delete.

Good luck. Always be extra careful when deleting with a script, you never know when you will blow away more than you wanted. Then you need to have a good backup to restore from. Ugly. Einstein47
(How come we never see the headline, &quot;Psychic Wins Lottery&quot;?)
 
Thanks everyone. I have tried to get these commands to work;however, the -mtime is not recognized. The command deletes the entire directory, which I want to keep 6 months. Any other scripts out there created to do this function, or ideas.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top