How to delete directories using rmdir command in Linux?

rmdir command in Linux is used to delete empty directories. Empty directory means a directory which do not have files or sub-directories. So, lets learn how to use mkdir command in Linux.

Syntax

$rmdir [OPTION]...DIRECTORY...

Example

How to use rmdir command in Linux

The example above shows the deletion of directory Dir using rmdir command in Linux.

Options used with rmdir in Linux

1. To delete hierarchy of directories

-p: option can help delete a hierarchy of directories.
Suppose you have a hierarchy of three directories A, B and C such that C is inside B and B is inside A.

tree command in linux

Now you can not use

$rmdir A

to delete directory A and its sub-directories. You will have to write

$rmdir A A/B A/B/C

As an alternate -p is helpful as:

$rmdir -p A/B/C

Note: Directory A most not have anything other than B and directory B must not have anything other C. This is because rmdir can remove empty directories only.

2. Get a diagnostic message for each directory processed

-v: option prints a message regarding what happened while using rmdir command with the directory. For example:

Shows that the directory B is being removed.

How to remove Non-Empty Directories?

Now an important issues arrive that how to delete non-empty directories. If you try using rmdir command to delete non-empty directories it will throw an error “Directory not empty”.

The solution is using the rm -r command. The rm command not only deletes files but can also delete non-empty directories by using the -r option. For example:

$rm -r <directory_name>

Practice questions on How to use rmdir command in Linux?

Q1. Consider a directory Music which contains a empty directory Hindi. Write the command to delete the directory Music using rmdir.
Q2. Create three directories (D1, D2 and D3) using mkdir command. How can you delete all the three directories using rmdir command only ones?

PPT on rmdir command

Video on rmdir command

Relevant Commands

touch
rm
mkdir
chmod

Leave a Reply

Your email address will not be published. Required fields are marked *