When you need to delete a file or a folder in Linux, the standard tool is the rm (remove) command. If you want to delete a folder and absolutely everything inside of it, you use the recursive flag: rm -r foldername.
However, running rm -r is highly dangerous. If you accidentally type the wrong folder name, Linux will instantly and permanently obliterate the folder, along with all of its files and subdirectories, without asking for confirmation. There is no Recycle Bin to recover them.
If you are simply trying to clean up your file system and delete directories that you believe are empty, you should use the rmdir (remove directory) command instead. It is significantly safer.
How rmdir Protects Your Data
The rmdir command has one strict, built-in rule: It will only delete a directory if it is 100% empty.
If you run the command on a folder that contains even a single file, or a hidden system file (like a .DS_Store or .gitignore file), the command will instantly fail, abort the deletion, and throw an error message to the terminal.
Syntax:
rmdir foldername
If the folder “Old_Projects” is truly empty, running rmdir Old_Projects will delete it silently. If there is a forgotten text file inside, you will receive this warning:
rmdir: failed to remove 'Old_Projects': Directory not empty
This failure is a feature, not a bug. It forces you to go into the directory and verify its contents before destroying it.
How to Delete Multiple Empty Directories at Once
If you have three empty folders in your current location, you don’t need to run the command three separate times. You can pass multiple arguments to rmdir separated by spaces.
rmdir folder1 folder2 folder3
Linux will evaluate each one independently. If folder2 has a file in it, it will fail to delete folder2, but it will still successfully delete the empty folder1 and folder3.
How to Delete a Chain of Empty Directories
Sometimes you have a nested folder structure where a parent folder contains a child folder, which contains a grandchild folder, and they are all completely empty (e.g., 2023/January/Photos).
Instead of deleting the inner folder, navigating out, deleting the middle folder, and so on, you can use the -p (parents) flag.
rmdir -p 2023/January/Photos
Linux will delete “Photos”. It will then notice that “January” is now empty, so it will delete that. It will then notice that “2023” is now empty, and delete that as well, cleaning up the entire empty chain in one swift command.