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.
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:
So if you had an empty directory named “test”, you can remove it with:
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:
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