The rmdir command is used to delete directories, but only if they are completely empty. It is a safe way to remove directories, as it prevents accidental deletion of folders that still contain files or other subdirectories.
Example 1: Remove a single empty directory
# Remove the empty directory named 'reports'
rmdir reports
Explanation: This command will delete the reports directory, but only if it contains no files or subdirectories. If the directory is not empty, the command will fail and display an error message.
Example 2: Remove multiple empty directories
# Remove the three specified empty directories
rmdir invoices quotes archive
Explanation: Similar to mkdir, you can provide a space-separated list of directory names to rmdir to remove them all with a single command. Each directory must be empty for the operation to succeed on it.
Example 3: Remove a nested empty directory structure
# Remove the 'invoices', '2025', and 'sales' directories if they are empty
rmdir -p sales/2025/invoices
Explanation: The -p (parents) option tells rmdir to remove the child directory (invoices) and then attempt to remove its parent directories (2025 and sales) as well. This only works if each directory becomes empty after its child is removed.
Example 4: Attempting to remove a non-empty directory
# Try to remove the 'project_alpha' directory which contains files
rmdir project_alpha
Explanation: If the project_alpha directory contains any files or other directories, this command will fail. The system will output an error like rmdir: failed to remove 'project_alpha': Directory not empty, preventing data loss.
Example 5: Removing a directory using an absolute path
# Remove the empty 'temp_data' directory located in '/var'
rmdir /var/temp_data
Explanation: You can specify the full path to a directory to remove it from anywhere in the filesystem. You must have the appropriate permissions on the parent directory (/var) to delete the subdirectory.
Example 6: Removing a directory with verbose output
# Remove the 'old_logs' directory and print a message for each removed directory
rmdir -v old_logs
Explanation: Using the -v (verbose) flag causes rmdir to print a diagnostic message for each directory it successfully processes and removes.
Example 7: Removing a directory with a space in its name
# Remove the empty directory named 'My Documents'
rmdir "My Documents"
Explanation: Just as when creating it, if a directory name contains spaces, you must enclose the entire name in quotes for the shell to correctly identify it as a single entity to be removed.