Remove or delete directory with Linux rmdir command

As a Linux user, you need to delete or remove unwanted directories in your system to make it clean and tidy. This tutorial will guide a new Linux user to delete directory in Linux using rmdir command.

Linux rmdir command

When there is tool to create something, there must be tool to remove it. The Linux rmdir command is the opposite tool of mkdir command. If mkdir command creates directory then the rmdir command removes directory, but only empty directory. Let's see what is written in rmdir manual page:

NAME
rmdir - remove empty directories

SYNOPSIS
rmdir [OPTION]... DIRECTORY...

DESCRIPTION
Remove the DIRECTORY(ies), if they are empty.

--ignore-fail-on-non-empty

ignore each failure that is solely because a directory is non-empty

-p, --parents
Remove DIRECTORY and its ancestors. E.g., `rmdir -p a/b/c' is similar
to `rmdir a/b/c a/b a'.

-v, --verbose
output a diagnostic for every directory processed

--help display this help and exit

--version
output version information and exit

As you can see, there is also not many options available with rmdir. The syntax is similar to the mkdir, just replace it with rmdir, rmdir <new directory>. Despite of the similarity, rmdir is not that popular because it can only delete an empty directory. That means, if a directory contains file or child directory, then rmdir is useless. You can't delete a directory without delete its content first.

Try this example:

[email protected]:~$ mkdir parent
[email protected]:~$ mkdir parent/child
[email protected]:~$ touch parent/file.txt
[email protected]e:~$ ls parent/
child/ file.txt
[email protected]:~$

We created a directory with a child and a file in it. Now let us try to delete the parent directory:

[email protected]:~$ rmdir parent/
rmdir: parent/: Directory not empty
[email protected]:~$

We can't delete the parent directory because it's not empty. Is that bad? No it's not. The rmdir reminds us that the directory is not empty. There maybe contains useful data. So, check that first, and if it's rubbish, then delete all the data and after that you can delete the directory itself.

Here is another good thing about Linux rmdir command:

[email protected]:~$ ls -l parent/
total 4
drwxr-xr-x 2 luzar users 4096 2008-12-18 03:15 child/
-rw-r--r-- 1 luzar users 0 2008-12-18 03:16 file.txt
[email protected]:~$ rm parent/file.txt
[email protected]:~$ rmdir -p parent/child/
[email protected]:~$ ls
Desktop/ testsamba/
[email protected]:~$

When using rmdir with -p option, rmdir will remove the parent as well (of course in condition the parent and child contain no file). So that concludes the rmdir command tutorial. If you want to more information about deleting Linux directory, for example, how to delete or remove directory with sub-directory and files in it, take a look at Linux rm command - delete file and directory in Linux tutorial.

Back to Linux basic commands main page.

Add new comment