Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using find to delete all subdirectories (and their files)

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.

like image 582
infmz Avatar asked May 05 '11 10:05

infmz


People also ask

How delete all files and subdirectories in Linux?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.

What command can be used to delete a directory recursively searching for files and other directories and deleting them?

To permanently remove a directory in Linux, use either rmdir or rm command: For empty directories, use rmdir [dirname] or rm -d [dirname] For non-empty directories, use rm -r [dirname]


Video Answer


2 Answers

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
like image 37
MarcoS Avatar answered Oct 03 '22 09:10

MarcoS


Try:

find /myDir -mindepth 1 -mtime 7 -exec rm -rf {} \;
like image 151
linuts Avatar answered Oct 03 '22 10:10

linuts