Linux Commands

How To Delete a Directory in Linux

Directories are containers that hold various data, including text, media, and zip files. As a system administrator, you can create, move, or delete these directories. Although deleting a directory in Linux is simple, many beginners need to learn the correct ways to do it. That’s why Linux users sometimes delete important directories, which can lead to major issues.

In this quick blog, we have included all the possible ways to delete a directory in Linux. Here, we have included commands and a simple GUI method to delete a directory without hassles. So let’s look at them all with the appropriate examples:

The rm Command

The rm command deletes files and directories, where ‘rm’ stands for ‘remove.’ You can use the following rm command to delete a directory:

rm -r directory_name

We use the ‘-r’ option to delete the target directory, its content, and subdirectories. For instance, let’s delete the music directory using the rm command:

rm -r Music

r-option-in-rm-command-to-delete-a-directory

Note: Be cautious using the rm command because it permanently deletes files and directories without confirmation.

The rmdir Command

Unlike rm, the rmdir command is designed to remove empty directories. For example, to delete an empty directory named Script located in the home directory, please use the following command:

rmdir ~/Script

rmdir-command-to-delete-a-directory

Note: When using the rmdir command, please specify the target directory and its path. Without the correct path, this command will result in an error.

Similarly, you can also use the rmdir to delete a subdirectory. For example, let’s delete the Images subdirectory available in the Documents directory:

rmdir ~/Documents/Images

rmdir-command-to-delete-a-subdirectory

The find Command

Despite the original function of the find command, it also lets you delete files and directories with its ‘-exec’ option. However, this feature is only applicable to empty directories. For example, to remove a directory this way, use:

find directory_name -type d -exec rm -r {} +

Here, the ‘-type d’ option specifies that the searched term is the name of a directory. The ‘-exec rm -r {} +’ option guides the find utility to execute the ‘rm -r’ command for every directory found with the input name. Moreover, replace the directory_name with the name of the directory you intend to remove:

find Scripts -type d -exec rm -r {} +

find-command-to-delete-a-directory

A Quick Summary

Deleting files and directories is a fundamental task for an everyday Linux user. This article demonstrated different methods for deleting a directory using appropriate examples: the rm, rmdir, and find commands. You can choose the rm to delete directories and files, whereas the rmdir only works to delete empty directories. Lastly, the find command allows you to delete directories with the help of the ‘-exec’ option.

About the author

Prateek Jangid