rmdir – remove empty directories

rmdir is one of the basic unix commands, which serves a sole purpose of removing empty directories. You may need this kind of functionality to attempt removing directories, and be sure that any files still existing in them will be safe. For removing any directory irregardless of any files in it, you should use the rm command.

To demonstrate how rmdir works, let's create two directories and two files in them:

ubuntu$ mkdir -p /tmp/dir1/dir2
ubuntu$ touch /tmp/dir1/file1
ubuntu$ touch /tmp/dir1/dir2/file2

This gives us the following file and directory structure:

ubuntu$ find /tmp/dir1

So, we have /tmp/dir1 directory, which contains a file1 file and a dir2 directory. /tmp/dir1/dir2 contains another file, called file2.

Basic rmdir usage

The simplest way to remove an empty directory is to run rmdir and supply the desired directory name as a command line parameter:

ubuntu$ rmdir /tmp/dir1/dir2
rmdir: `/tmp/dir1/dir2': Directory not empty

In our example, we got the error because dir2 contains a file2 file, so it cannot be removed until the file exists.

Now, if we remove the file2 in dir2 directory, rmdir will happily destroy dir2 if we try again:

ubuntu$ rm /tmp/dir1/dir2/file1
ubuntu$ rmdir /tmp/dir1/dir2

Cascade directory removal with mkdir

If you want, you can attempt to do a cascade directory removal – if removing a specified directory succeeds, rmdir will try to remove its parent directory, if it's empty, and move up the directory tree until it meets a directory which isn't empty or which your use doesn't have permission to remove.

This kind of directory removal is achieved using rmdir -p option. If we recreate the dir2 directory under dir1 from our initial setup, you can see how rmdir will remove dir2 and then attempt to remove dir1, its parent directory:

ubuntu$ mkdir /tmp/dir1/dir2
ubuntu$ rmdir -p /tmp/dir1/dir2
rmdir: `/tmp/dir1': Directory not empty

Now, the /tmp/dir1 removal is failed because it has file1 file left it it. So if we remove it and recreate the empty dir2, rmdir -p will successfully remove both directories.

First, let's prepare our 2 empty directories:

ubuntu$ rm /tmp/dir1/file1
ubuntu$ mkdir /tmp/dir1/dir2

This is how we double-check it's only dir1 with dir2 subdirectory:

ubuntu$ find /tmp/dir1

And now let's see how rmdir -p manages to remove both and even attempt to remove /tmp, cause it's the parent of /tmp/dir1:

ubuntu$ rmdir -p /tmp/dir1/dir2
rmdir: `/tmp': Permission denied

As usual, unix find command can testify that there's no /tmp/dir1 directory anymore:

ubuntu$ find /tmp/dir1
find: /tmp/dir1: No such file or directory

See also:

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS