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

rmdir [options] directory_name
  • [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:

rmdir empty_folder

Output: If the directory is empty, there will be no output, and the directory will be deleted successfully.

Example:

$ mkdir empty_folder $ rmdir empty_folder $ ls

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.

$ mkdir non_empty_folder $ touch non_empty_folder/file.txt $ rmdir non_empty_folder

Output:

rmdir: failed to remove 'non_empty_folder': Directory not empty

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:

$ mkdir -p parent/child/grandchild $ rmdir -p parent/child/grandchild $ ls parent

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:

$ mkdir -p parent/child/grandchild $ touch parent/child/file.txt $ rmdir -p parent/child/grandchild

Output:

rmdir: failed to remove 'parent/child': Directory not empty

Here, grandchild is deleted if it’s empty, but rmdir fails to remove parent/child because it contains file.txt.

Summary Table

CommandDescriptionExample Output
rmdir empty_folderDeletes an empty directory(No output if successful)
rmdir non_empty_folderFails if the directory is not emptyDirectory not empty error
rmdir -p parent/child/grandchildDeletes nested empty directories(No output if all are empty)
rmdir -p path/to/dir (with files)Stops at first non-empty directoryDirectory 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.