How To Delete Directory In Linux

One of the most common tasks when working with an operating system is to delete files or directories. In this blog post, we will guide you on how to delete a directory in Linux using the rm and rmdir commands.

Deleting a Directory Using the rmdir Command

The most straightforward method to delete a directory in Linux is to use the built-in rmdir command. The rmdir command removes the DIRECTORY(ies), if they are empty.

Here is the basic syntax for the rmdir command:

    rmdir directory_name
    

The command will delete the specified directory assuming it is empty. If the directory is not empty, you will get an error message.

Deleting a Directory Using the rm Command

In case the directory is not empty and you want to delete it along with its contents, you will have to use the rm command with the -r (or –recursive) option. This tells the system to remove the directory and its contents recursively.

Here is the syntax for the rm command to delete a directory:

    rm -r directory_name
    

Be extremely careful when using the rm -r command, as it will not prompt you for confirmation before deleting the files. If you want to be prompted for confirmation for each file, use the -i (interactive) option:

    rm -ri directory_name
    

This will prompt you with a confirmation message for each file inside the directory.

Conclusion

Deleting directories in Linux can be easy once you are aware of the rmdir and rm commands. Remember that using these commands, especially the rm -r command, should be done with care to avoid accidentally deleting important files.