Linux rmdir Command
The rmdir
command in Ubuntu is used to remove empty directories only. If a directory contains any files or subdirectories, rmdir
will not delete it and will return an error message.
Syntax
[options]
: Optional flags to modify the command's behavior.directory_name
: Name of the directory to remove.
Examples with Output
1. Removing a Single Empty Directory
To delete a single empty directory, use:
Output: If the directory is empty, there will be no output, and the directory will be deleted successfully.
Example:
If empty_folder
was deleted, ls
will show no trace of it.
2. Attempting to Remove a Non-Empty Directory
If you try to delete a directory that contains files or other directories, rmdir
will return an error.
Output:
In this case, rmdir
fails because non_empty_folder
contains a file (file.txt
).
3. Using the -p
Option to Remove Parent Directories
The -p
option allows you to delete a directory and its parent directories if they are empty. This is useful for removing nested empty directories in a single command.
Example:
Output: If all directories are empty, they will be removed, and there will be no output.
However, if any directory in the path contains files, rmdir
will stop and show an error:
Output:
Here, grandchild
is deleted if it’s empty, but rmdir
fails to remove parent/child
because it contains file.txt
.
Summary Table
Command | Description | Example Output |
---|---|---|
rmdir empty_folder | Deletes an empty directory | (No output if successful) |
rmdir non_empty_folder | Fails if the directory is not empty | Directory not empty error |
rmdir -p parent/child/grandchild | Deletes nested empty directories | (No output if all are empty) |
rmdir -p path/to/dir (with files) | Stops at first non-empty directory | Directory not empty error |
Summary
The rmdir
command in Ubuntu is straightforward for removing empty directories, and using the -p
option allows you to remove a hierarchy of empty directories. For non-empty directories, use rm -r
instead.