How do I remove a directory and all its contents?

In bash all I know is that

rmdir directoryname

will remove the directory but only if it’s empty. Is there a way to force remove subdirectories?

Asked By: Piper

||

The following command will do it for you. Use caution though if this isn’t your intention as this also removes files in the directory and subdirectories.

rm -rf directoryname
Answered By: Phillip Nordwall

if rm -rf directoryname fails you, try using rm -R -f directoryname, or rm --recursive -f directoryname.

If you are not having any luck with these, you should consider reinstalling rm or switching shells.

Answered By: saterHater

Other answers show how to completely remove a directory’s content, but IMO they don’t address the literal question of the original post — that is, how can one delete subdirectories (as opposed to usual files). In other words, how can one delete empty directory structures while keeping subdirectories containing files ?

This can be achieved with find :

find directoryname -type d -delete

This command will recursively search for directories (-type d) through directoryname and -delete them only if their subdirectories or themselves don’t contain any files.

Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.