Alex Rivera | Logout

Using find to delete all subdirectories (and their files)

Asked 2011-05-05T10:28:14.027
18

I'm sure this is straight forward and answered somewhere, but I didn't manage to find what I was looking for. Basically, I'm trying to run a cron script to clear the contents of a given directory every 7 days. So far I have tried the following,

find /myDir -mtime 7 -exec rm -rf {} \;

This however also deletes the parent directory myDir, which I do not want. I also tried,

find /myDir -type f -type d -mtime 7 -delete

which appeared to do nothing. I also tried,

fnd /myDir -type d -delete

which deleted all but the parent directory just as I need. However, a warning message came up reading,

relative path potentially not safe

I'd appreciate if anyone can rectify my script so that it safely deletes all subdirectories in folder.

Many thanks. =)

UPDATE: I decided to go for the following,

find /myDir -mindepth 1 -mtime 7 -delete

Based upon what I learned from all who replied. Again, many thanks to you all.

Edit
Report

1 Answer

7

What about

cd myDir/ ; find . -type d -delete

assuming that you run this from myDir parent directory.

If you can't guarantee myDir exists, then this is safer:

cd myDir/ && find . -type d -delete
answered 2011-05-05T10:37:45.947

Your Answer