Linux, Web Hosting, and Everything Else in Between
Linux, Web Hosting, and Everything Else in Between

How to Remove a Directory in Linux

remove directory in linux



Our second quick and short tutorial. Before, we showed you how to rename a file in Linux. Now we’re going to show you how to remove a directory in Linux.

Like most other basic commands, these will work on most Linux-based distros, including CentOS and Ubuntu. The most common usage is on cloud servers.

Generally, you’ll use the “rm” command to remove files and directories in Linux. But, there are different use cases and different commands, so we’ll go through them below.

Remove an empty directory

To remove an empty directory (folder), you can use the “rmdir” command. The syntax is:

rmdir directoryname

So if you had an empty directory named “test”, you can remove it with:

rmdir test

But, if the directory had files in it, you would not be able to remove it with “rmdir”. If you tried removing a directory with files, you would get an error like this:

rmdir: failed to remove 'directoryname': Directory not empty

Instead, you should use a different command.

Remove a directory with files and subdirectories (non-empty directory)

Here’s where we would use the “rm” command. You can also remove empty directories with the “rm” command, so you can always use that one.

So, if we had a directory with subdirectories and files in it, we would use this syntax:

rm -r directoryname

We used the option “-r” to recursively delete all subdirectories (subfolders) and files in the parent directory.

If you don’t use the “-r” option, you will only delete a single file. With our command, we deleted all contents (files and directories) within the parent directory.

Remove a single file

To remove a single file, you can use the “rm” command with no additional options:

rm file.txt

And that’s it. Those were the most common commands for removing a directory in Linux.

Tip: don’t always use the -f option

When using the “rm” command, you should not always use the “-f” (force) option. By using that option, you won’t get any warnings or prompts when removing something. And it’s always better to have a warning or a prompt before removing something, just to make sure you’re doing the right thing.

If you get a “permission denied” (or similar) error

If you get a “permission denied” error or any other similar error, then you are probably using a non-root user. You should either use the root user or use sudo to run the commands. So just append “sudo” to each command and enter your sudo password when prompt:

sudo rm -r directoryname

Leave a Reply to kiki Cancel reply

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

9 thoughts on “How to Remove a Directory in Linux”