The rmdir
command in Linux is used to remove empty directories. It only works for directories that are empty, and if you try to remove a directory with content, it will fail.
Here are some examples of how to use the rmdir
command:
1. Basic Usage: Remove an Empty Directory
To remove an empty directory, simply run:
rmdir directory_name
Example:
rmdir myfolder
This will remove the myfolder
directory if it is empty.
2. Remove Multiple Empty Directories
You can remove multiple empty directories at once by providing their names:
rmdir dir1 dir2 dir3
Example:
rmdir folder1 folder2 folder3
This will remove all three directories if they are empty.
3. Using -p
Option: Remove Empty Parent Directories
The -p
option will remove a directory and its parent directories if they are empty.
rmdir -p parent/child/grandchild
Example:
rmdir -p /home/user/Documents/emptyfolder/emptydir
If the emptyfolder
and emptydir
are empty, this will remove them and their parent directories.
4. Error When Directory is Not Empty
If the directory is not empty, rmdir
will give an error:
rmdir nonemptyfolder
Output:
rmdir: failed to remove 'nonemptyfolder': Directory not empty
5. Check if Directory is Empty
Before removing a directory, you might want to confirm whether it’s empty. You can use ls
or find
:
ls emptyfolder
If it lists files, the directory is not empty. If nothing shows, it’s empty, and you can remove it with rmdir
.
Key Points:
rmdir
only removes empty directories.- Use
-p
to remove a directory and its empty parents. - To delete non-empty directories, you would use
rm -r
(recursive) instead ofrmdir
.