Tuesday, March 03, 2009

Howto: Delete Empty Directories [Unix]

Consider the following directory structure:
/tmp
 |-->bar.txt
 |-->dir1/
 |-->dir2/
 |    |-->baz.txt
 |-->dir3/
 |-->foo.txt
There are two files called bar.txt and foo.txt, a non-empty directory called dir2 and two empty directories called dir1 and dir3.

This is how you can delete only the empty directories:

sharfah@starship:/tmp> unalias rmdir
sharfah@starship:/tmp> rmdir *
rmdir: directory "bar.txt": Path component not a directory
rmdir: directory "dir2": Directory not empty
rmdir: directory "foo.txt": Path component not a directory
You need to unalias rmdir just in case you have it aliased to "rm -rf"! You will notice that rmdir does not delete files or non-empty directories. Only dir1 and dir3 are deleted.

Another way to do it, using find:

sharfah@starship:/tmp> find . -type d -exec rmdir {} \;
rmdir: directory ".": Can't remove current directory or ..
rmdir: directory "./dir2": Directory not empty
Note that aliases aren't recognised by find, so even if you did have rmdir aliased, it would not use it.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.