Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

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

i had to do a script job in bash to delete all directory in a path which are older than a specified date except some of them. i know the name of the directories which shouldn't be deleted...

Can you help me???

i'm sorry but i'm a beginner...

lot of thanks!

share|improve this question
Please don't cross-post. – Dennis Williamson Jan 25 '11 at 20:28

try tmpwatch with the exclude options -x and -X

man tmpwatch for more info.

I've never used it myself with the excludes so i cant provide examples, but im pretty sure that'll work.

share|improve this answer
sorry i've not tmpwatch on my version... – mikjcl Jan 25 '11 at 15:04
@mikjcl <- Easy enough to install -- and a better option than the ghetto solution I'm about to post – voretaq7 Jan 25 '11 at 15:06

This must be my find day.

find /yourpath -mmin +60 -type d -not \( -name dirname1 -o -name dirname2 \) -print0 | xargs -0 rm -r

will find and delete all directories older than 60 minutes (adapt accordingly) which are not named dirname1 or dirname2. You can extend this list with additional -o name dirname parts. Also, I would strongly recommend to replace the rm -r part with echo for testing.

share|improve this answer
Cool, more elegant than what I was going to propose (shell hack) – voretaq7 Jan 25 '11 at 15:19
it'll be perfect even if my version don't understand "-not" – mikjcl Jan 25 '11 at 16:27

For GNU find:

find . ! -newermt 2010/10/01 -type d -regextype posix-egrep ! -regex '^.*/(foo|bar|baz)/?.*' -exec echo rm -rf {} +

This will find and delete directories older than the given date that do not match the regular expression. Change "foo", etc., to match your directory names. Separate each name using |. Remove the echo when you're finished testing. The modification time is checked, change to -newerat to check the access time instead.

share|improve this answer

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.