Introduction
Likewise mkdir command for creating directories, the rmdir command (remove directory) helps Linux system users to remove directory(ies). But rm command can also be used to remove a directory. It is useful when you want to delete an empty directory.
Note: rmdir can only remove blank directories.
In this article i will guide you how you can make use of rmdir command to remove directory.
Synopsis / Syntax
The general syntax for rmdir command is as below.
$ rmdir [OPTION]… DIRECTORY…
For Example: For deleting a directory named thecloudiary, the argument will be as below.
$ rmdir thecloudiary
But remember thecloudiary directory must be empty.
Options
There are very less options in rmdir command. Let us discuss all the options.
Option | Description |
-p, –parents | remove DIRECTORY and its ancestors |
-v, –verbose | Shows message being what has been done |
–help | display this help and exit |
How to Remove (Delete) an empty Directory ?
To remove an empty directory just simply run the command.
$ rmdir Directory_Name
You can delete more than one directory with one command. As you have the facility to create multiple files in mkdir command in one shot.
While trying to delete a non-empty directory you will get the below error and Linux system won’t allow you to delete the directory. You can use rm command to delete the non-empty directory.
Output:
rmdir: failed to remove 'Directory_Name': No such file or directory
How to delete multiple empty directories ?
As you have seen in mkdir command we have created directories in forward order. But when invoking rmdir command it should be in reverse order.
The below sequence used in mkdir is invalid in rmdir.
$ rmdir X X/X1 X/X2 Output: rmdir: failed to remove 'x': Directory not empty
But here after running this command rmdir has silently deleted the sub-directories X1 and X2.
If you run the below command it will delete the parent and its child directories.
$ rmdir -v X/X2 X/X1 X
Output:
Here I have used -v option to see what is being done.
If you wanted to delete multiple directories under a parent directory invoke the below command.
$ rmdir dir1 dir2 dir3
Rules to delete directory
While deleting directory you should remember these two rules.
- You can not delete a directory with rmdir unless it is empty.
- You can not remove a sub-directory unless you are placed in a directory which is hierarchically above the one yo have wished to remove.
Conclusion
The rmdir command only works for those directories owned by the user. You can remove the directory without using rmdir command. Check it out.
In this article a basic understanding of rmdir is explained, leave a comment if have any queries.