If you need to remove a directory on Linux, whether it’s empty or not, it’s easy to do Let’s walk through how you can do this in a few simple steps.
1. Open Your Terminal
First, you need to open your Terminal. This is where you’ll run commands to interact with your system. You can open it by searching for “Terminal” in your app menu or by pressing Ctrl + Alt + T
.
2. Remove an Empty Directory Using rmdir
If the directory you want to remove is empty, you can use the rmdir
command. This command removes only empty directories.
Here’s the basic syntax:
rmdir directory_name
For example, to remove a directory named old_folder
, you would type:
rmdir old_folder
If the directory is not empty, the command will fail with an error message saying it’s not empty.
3. Remove a Directory and Its Contents Using rm -r
If the directory you want to remove contains files or other directories, you can use the rm
command with the -r
(recursive) option. This will remove the directory and everything inside it (be careful with this one!).
Here’s the syntax:
rm -r directory_name
For example, to remove a directory named old_folder
and all its contents, you would type:
rm -r old_folder
This will remove the directory and all files or subdirectories inside it.
4. Force Removal with rm -rf
(Be Cautious!)
If you’re absolutely sure you want to remove a directory and all its contents, and you don’t want to be prompted for confirmation (in case there are write-protected files), you can use the -f
(force) option:
rm -rf directory_name
For example, to remove the directory old_folder
and all its contents without any prompts:
rm -rf old_folder
Warning: The rm -rf
command is powerful and dangerous. Once executed, the directory and its contents are permanently deleted, and you cannot recover them easily.
5. Verify the Directory is Removed
You can confirm that the directory has been removed by listing the contents of the parent directory with the ls
command:
ls
If the directory has been successfully removed, it will no longer appear in the list.