How to use rmdir command in Linux?

There are multiple ways to create or remove directories in a Linux system. You can create it from GUI or using a terminal. Knowing how to create or remove directories using commands can be very useful because most Linux systems offer only a command-line interface to perform a task.

I already explained how to use mkdir command to create directories on Linux. In this article, I will discuss the rmdir command which is used to delete an empty directory from a Linux system.

The syntax of rmdir command in Linux

The syntax of how to use rmdir command in Linux is given below.

rmdir [OPTION]... DIRECTORY(s)...

Where you can use the given options with this command.

--ignore-fail-on-non-empty – Using this option with rmdir command will not report a failure that occurs solely because a directory is non-empty. Normally, when rmdir is used to remove a non-empty directory, it reports an error.

-p, --parents – Remove a directory with its parent directories

-v, --verbose – It displays verbose information for every directory being processed.

--help – Display help on how to use rmdir command

--version – Display version of rmdir and exit

Examples of using rmdir command in Linux

Some example of how to use rmdir command to remove a directory from your Linux system.

Basic usage of rmdir command

The most basic use of the rmdir command is to pass the directory name as an argument if you want to delete it. Please note this directory should be empty otherwise it will through an error.

rmdir testDir

Similarly, you can use this command to delete multiple empty directories.

rmdir testDir testDir1 testDir2

How to make rmdir ignore non-empty directories

When you try to remove a non-empty directory using rmdir command it will throw an error. By using the –ignore-fail-on-non-empty option you can suppress this error.

For example –

Here I am going to remove testDir which is a non-empty directory.

rmdir --ignore-fail-on-non-empty testDir

Use rmdir to remove parent directories as well

By using the option -p or --parents with rmdir command, you can delete a directory with its parent directories in a single command

Now see the given image –

The following command will delete all the directories i.e testDir, Dir1, docDir.

rmdir -p testDir/Dir1/docDir

How to delete a non-empty directory in Linux

There is no way to delete a non-empty directory using rmdir command. To delete a directory that contains files and directories you can use the rm command.

For example –

rm -d dir(s)

This will delete the directory as well as the content inside it.

Conclusion

I hope now you understand the usage of rmdir command in Linux. Now if you have a query then write us in the comments below.

Leave a Comment