Linux remove directory tutorial

Just like the folders in Windows, the Directory is a location where different files and documents are to be stored, moreover, these directories are a part of a hierarchical file system like Unix and Linux. Sometimes we have to delete or remove the directories in the Linux operating system to free up the memory space so that new files and directories can be created.

In this write-up, we will discover the methods by which we can remove the directories in the Linux operating system.

How to remove directories using the rmdir command

We can delete the empty directories only with the help of the rmdir command, for example, we have an empty directory with the name “MyDirectory”, and a non-empty directory, “MyDocuments”, we will first confirm both directories presence using the ls command:

$ ls

Now we will remove the empty directory, “MyDirectory” using the rmdir command:

$ rmdir MyDirectory

To confirm the removal of the “MyDirectory”, we will again list down the contents:

$ ls

After this we will try to remove the non-empty directory, “MyDocuments” using the rmdir command:

$ rmdir MyDocuments

We can see the error has been generated saying the directory is not empty which implies the rmdir command do not remove the non-empty directories.

How to remove directories using the rm command

The “rm” command is used to remove both the empty and non-empty directories from the Linux operating system, for example, we will use the rm command to remove the non-empty directory, “MyDocuments” using the command:

$ rm -r MyDocuments

The rm command by default only delete the files, not directories but in order to delete the directories, we have to use the “-r” option, which will remove the non-empty directory along with all the files included in the directory, to confirm the removal, we will list down the contents:

$ ls

How to delete all the empty directories using the find command

We can delete all the empty directories by using the find command, in order to understand it, we will create some empty directories using the mkdir command:

$ mkdir directory1 directory2 directory3

To confirm the creation of the directories, we will run the ls command:

$ ls

Now, we will use the find command to remove all these empty directories using the command:

$ find -type d -empty -delete

The empty directories have been removed, to confirm this we will use the command:

$ ls 

Conclusion

The directories are being made in the the Linux to stored the files and documents, but sometimes, these directories are of no use and they are just occupying th space on the memory of the computer. To get rid of these directories we will remove them and different methods of removing the directories in the Linux has been discussed in this article.