How to Use rmdir Command in Linux: Syntax and Examples
The
rmdir command in Linux removes empty directories. Use rmdir directory_name to delete a directory only if it is empty; otherwise, it will show an error.Syntax
The basic syntax of the rmdir command is:
rmdir [options] directory_name
Here, directory_name is the name of the empty directory you want to remove. Options can modify the behavior, such as removing parent directories if they become empty.
bash
rmdir [options] directory_name
Example
This example shows how to create an empty directory and then remove it using rmdir. It demonstrates that rmdir only works on empty directories.
bash
mkdir testdir rmdir testdir rmdir testdir
Output
rmdir: failed to remove 'testdir': No such file or directory
Common Pitfalls
A common mistake is trying to remove a directory that is not empty, which causes rmdir to fail. Also, trying to remove a directory that does not exist will show an error.
To remove a directory with files, use rm -r directory_name instead.
bash
mkdir testdir mkdir testdir/subdir rmdir testdir
Output
rmdir: failed to remove 'testdir': Directory not empty
Quick Reference
| Command | Description |
|---|---|
| rmdir directory_name | Remove an empty directory |
| rmdir -p dir1/dir2 | Remove directory and its empty parent directories |
| rm -r directory_name | Remove directory and its contents recursively (use with caution) |
Key Takeaways
Use
rmdir only to remove empty directories.Trying to remove a non-empty directory with
rmdir causes an error.Use
rm -r to remove directories with files inside.The
-p option removes parent directories if they become empty.Always double-check directory contents before removing to avoid data loss.