Understanding the rmdir
Command in Linux: Removing Empty Directories
1. Introduction
The rmdir
command in Linux is a specialized utility designed to remove empty directories, ensuring a safe and controlled way to clean up your file system. Unlike the rm -r
command, which can delete directories and their contents recursively, rmdir
is inherently safer because it will fail if the directory contains any files or subdirectories. This prevents accidental data loss, making rmdir
a preferred choice for tasks where you only want to remove directories you know are empty.
2. Basic Syntax
The basic syntax for the rmdir
command is:
# Display the basic usage of the rmdir command with optional flags and directory names
$ rmdir [OPTION]... DIRECTORY...
- OPTION: Optional flags that modify the command’s behavior, such as
-p
for removing parent directories or-v
for verbose output. - DIRECTORY…: One or more directory names to remove. These can be specified as relative paths (e.g.,
my_dir
) or absolute paths (e.g.,/tmp/my_dir
). The directories must be empty forrmdir
to succeed.
Note: rmdir
processes directories in the order they are listed, and it will stop processing a directory if it encounters an error (e.g., a non-empty directory) but will continue with the remaining directories unless otherwise specified.
3. Core Use Cases with Examples
To demonstrate rmdir
’s functionality, let’s set up a test environment. The following commands create a directory structure for our examples:
# Create a directory named rmdir_test_area to serve as the test environment
$ mkdir rmdir_test_area
# Change the current working directory to rmdir_test_area
$ cd rmdir_test_area
# Create three empty directories named empty_dir1, empty_dir2, and temp_logs
$ mkdir empty_dir1 empty_dir2 temp_logs
# Create a directory named dir_with_content that will be non-empty
$ mkdir dir_with_content
# Create a file named some_file.txt inside dir_with_content to make it non-empty
$ touch dir_with_content/some_file.txt
# Create a nested directory structure with parent_dir containing child_dir containing grandchild_dir, all empty
$ mkdir -p parent_dir/child_dir/grandchild_dir
Verify the setup:
# List the contents of the current directory with classification (directories end with /)
$ ls -F
dir_with_content/ empty_dir1/ empty_dir2/ parent_dir/ temp_logs/
# List the contents of dir_with_content to confirm it contains a file
$ ls -F dir_with_content/
some_file.txt
# List the contents of parent_dir/child_dir to confirm it contains grandchild_dir
$ ls -F parent_dir/child_dir/
grandchild_dir/
3.1. Removing a Single Empty Directory
If a directory is empty, rmdir
removes it without any additional options.
# Remove the empty directory named empty_dir1
$ rmdir empty_dir1
# List the contents of the current directory to confirm empty_dir1 is removed
$ ls -F
dir_with_content/ empty_dir2/ parent_dir/ temp_logs/
Explanation: The empty_dir1
directory is removed because it contains no files or subdirectories. The ls -F
command confirms its absence.
3.2. Removing Multiple Empty Directories
You can specify multiple empty directories in a single command.
# Remove multiple empty directories named empty_dir2 and temp_logs in one command
$ rmdir empty_dir2 temp_logs
# List the contents of the current directory to confirm empty_dir2 and temp_logs are removed
$ ls -F
dir_with_content/ parent_dir/
Explanation: Both empty_dir2
and temp_logs
are removed as they are empty. The command processes directories sequentially, and ls -F
shows they are no longer present.
3.3. Attempting to Remove a Non-Empty Directory (Fails)
rmdir
will fail if the directory contains files or subdirectories, which is its primary safety feature.
# Attempt to remove the non-empty directory named dir_with_content, which should fail
$ rmdir dir_with_content
rmdir: failed to remove 'dir_with_content': Directory not empty
Explanation: The dir_with_content
directory contains some_file.txt
, so rmdir
refuses to delete it, ensuring no data is lost. The error message is clear and specific.
3.4. Removing an Empty Directory Using an Absolute Path
You can use an absolute path to remove an empty directory, which is useful when working outside the current directory.
# Create an empty directory named my_empty_temp_dir in the /tmp directory
$ mkdir /tmp/my_empty_temp_dir
# Remove the empty directory my_empty_temp_dir using its absolute path
$ rmdir /tmp/my_empty_temp_dir
# Attempt to list the directory my_empty_temp_dir to confirm it has been removed
$ ls -d /tmp/my_empty_temp_dir
ls: cannot access '/tmp/my_empty_temp_dir': No such file or directory
Explanation: The directory /tmp/my_empty_temp_dir
is created and then removed using its absolute path. The ls -d
command confirms it no longer exists.
3.5. Removing Nested Empty Directories Sequentially
To remove nested directories, you must specify them in order from deepest to shallowest, or rmdir
will fail if a parent directory is not empty.
# Remove nested empty directories sequentially starting from the deepest level: grandchild_dir, then child_dir, then parent_dir
$ rmdir parent_dir/child_dir/grandchild_dir parent_dir/child_dir parent_dir
# Attempt to list the parent_dir directory to confirm it has been removed
$ ls -d parent_dir
ls: cannot access 'parent_dir': No such file or directory
Explanation: The directories are removed in order, ensuring each parent is empty before deletion. This manual approach is less common than using the -p
option (see below).
4. Key Options Explained (with Examples)
rmdir
has a limited but powerful set of options to enhance its functionality. Below, each option is explained with practical examples, ensuring you understand their use and impact.
4.1. -p, --parents
: Remove Parent Directories if They Become Empty
Purpose: Removes the specified directory and its parent directories up the path, provided they become empty after the child’s removal. This is equivalent to manually removing directories from deepest to shallowest.
Syntax: rmdir -p path/to/nested/directory
Example:
Using the nested structure parent_dir/child_dir/grandchild_dir
:
# Recursively list the contents of parent_dir to display the nested directory structure
$ ls -R parent_dir/
parent_dir/:
child_dir/
parent_dir/child_dir:
grandchild_dir/
parent_dir/child_dir/grandchild_dir:
# Remove the nested directories parent_dir/child_dir/grandchild_dir and its parents if they become empty using the -p option
$ rmdir -p parent_dir/child_dir/grandchild_dir
# Attempt to list the parent_dir directory to confirm it has been removed
$ ls -d parent_dir
ls: cannot access 'parent_dir': No such file or directory
Explanation: rmdir -p
removes grandchild_dir
, then checks if child_dir
is empty and removes it, and finally checks and removes parent_dir
if empty. The process stops if any directory is not empty or if permissions are insufficient.
Another Example (with a non-empty parent):
# Create a nested directory structure with directories a, b, and c
$ mkdir -p a/b/c
# Create a file named some_other_file.txt in directory a to make it non-empty
$ touch a/some_other_file.txt
# Attempt to remove the nested directories a/b/c using -p; it will remove c and b but stop at a due to the file
$ rmdir -p a/b/c
# Recursively list the contents of directory a to confirm only a remains with its file
$ ls -R a/
a/:
some_other_file.txt
Explanation: rmdir -p
removes c
and b
, but stops at a
because it contains some_other_file.txt
. This demonstrates the safety of -p
, as it only removes directories that become empty.
4.2. -v, --verbose
: Output a Message for Every Directory Processed
Purpose: Provides confirmation by printing a message for each directory processed, whether successfully removed or not.
Syntax: rmdir -v DIRECTORY...
Example:
# Create two empty directories named verbose_test1 and verbose_test2 for testing the verbose option
$ mkdir verbose_test1 verbose_test2
# Remove the directories verbose_test1 and verbose_test2 with verbose output to see confirmation messages
$ rmdir -v verbose_test1 verbose_test2
rmdir: removing directory, 'verbose_test1'
rmdir: removing directory, 'verbose_test2'
Explanation: The -v
option confirms each directory’s removal, making it useful for debugging or logging in scripts.
Example with -p
and -v
:
# Create a nested directory structure with directories deep, nested, and empty
$ mkdir -p deep/nested/empty
# Remove the nested directories deep/nested/empty and its parents with -p and -v options for parent removal and verbose output
$ rmdir -pv deep/nested/empty
rmdir: removing directory, 'deep/nested/empty'
rmdir: removing directory, 'deep/nested'
rmdir: removing directory, 'deep'
Explanation: Combining -p
and -v
provides detailed feedback as each directory in the path is removed, enhancing transparency.
4.3. --ignore-fail-on-non-empty
: Do Not Report Failure for Non-Empty Directories
Purpose: Suppresses error messages when rmdir
encounters a non-empty directory, allowing the command to continue processing other directories. The non-empty directory remains intact.
Syntax: rmdir --ignore-fail-on-non-empty DIRECTORY...
Example:
# Attempt to remove the non-empty directory dir_with_content with --ignore-fail-on-non-empty; no error will be reported
$ rmdir --ignore-fail-on-non-empty dir_with_content
# List the directory dir_with_content to confirm it still exists since it was non-empty
$ ls -d dir_with_content/
dir_with_content/
Explanation: Without --ignore-fail-on-non-empty
, attempting to remove dir_with_content
would produce an error. With this option, no error is displayed, and the command silently skips the non-empty directory. This is particularly useful in scripts where you want to attempt removal without halting on errors.
4.4. --help
: Display Help and Exit
Purpose: Displays a concise help message summarizing rmdir
’s options and usage, then exits.
Syntax: rmdir --help
Example:
# Display the help message for the rmdir command, showing available options and usage
$ rmdir --help
Usage: rmdir [OPTION]... DIRECTORY...
Remove the DIRECTORY(ies), if they are empty.
--ignore-fail-on-non-empty
ignore each failure that is solely because a
directory is non-empty
-p, --parents remove DIRECTORY and its ancestors; e.g., 'rmdir -p a/b/c' is
similar to 'rmdir a/b/c a/b a'
-v, --verbose output a diagnostic for every directory processed
--help display this help and exit
--version output version information and exit
Explanation: This option is useful for quick reference without consulting the manual page (man rmdir
).
4.5. --version
: Output Version Information and Exit
Purpose: Displays the version of the rmdir
utility, which is part of the GNU coreutils package, then exits.
Syntax: rmdir --version
Example:
# Display the version information for the rmdir command
$ rmdir --version
rmdir (GNU coreutils) 8.32
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
Explanation: This is useful for checking the installed version, especially when troubleshooting or ensuring compatibility.
5. Combining Options
Options can be combined to enhance rmdir
’s functionality. The most common combination is -p
and -v
, which removes parent directories and provides verbose output.
Example:
# Create a nested directory structure with directories scripts, logs, and archives
$ mkdir -p scripts/logs/archives
# Remove the nested directories scripts/logs/archives and its parents with -p and -v options for parent removal and verbose output
$ rmdir -pv scripts/logs/archives
rmdir: removing directory, 'scripts/logs/archives'
rmdir: removing directory, 'scripts/logs'
rmdir: removing directory, 'scripts'
Explanation: The -p
option removes the nested directories, and -v
confirms each removal. This combination is ideal for cleaning up complex directory structures while tracking progress.
Another Example (with --ignore-fail-on-non-empty
):
# Create a nested directory structure with directories test and dir
$ mkdir -p test/dir
# Create a file named file.txt in the test directory to make it non-empty
$ touch test/file.txt
# Remove test/dir (which is empty) and attempt to remove test (which is non-empty) with verbose output and ignoring failures on non-empty directories
$ rmdir -v --ignore-fail-on-non-empty test/dir test
rmdir: removing directory, 'test/dir'
Explanation: The test/dir
is empty and removed, but test
contains file.txt
. The --ignore-fail-on-non-empty
option prevents an error for test
, and -v
confirms the removal of test/dir
.
6. Handling Special Cases
rmdir
is simple, but certain scenarios require special handling to avoid errors or unexpected behavior.
6.1. Directory Names Starting with Hyphen
Directory names starting with a hyphen (e.g., -old_logs
) may be interpreted as options. Use --
to indicate the end of options or prefix with ./
.
# Create a directory named -old_logs with a hyphen, using -- to indicate the end of options
$ mkdir -- -old_logs
# Remove the directory -old_logs using -- to handle the hyphen in the name
$ rmdir -- -old_logs
# OR
# Remove the directory -old_logs by prefixing with ./ as an alternative method
$ rmdir ./-old_logs
# Attempt to list the directory -old_logs to confirm it has been removed
$ ls -d -old_logs
ls: cannot access '-old_logs': No such file or directory
Explanation: The --
separator ensures -old_logs
is treated as a directory name, not an option. This is a standard convention in Linux commands.
6.2. Directory Names with Spaces
Directories with spaces require quoting or escaping to be processed correctly.
# Create a directory named My Empty Folder with spaces in its name
$ mkdir "My Empty Folder"
# Remove the directory My Empty Folder using quotes to handle the spaces
$ rmdir "My Empty Folder"
# OR
# Remove the directory My Empty Folder by escaping the spaces with backslashes
$ rmdir My\ Empty\ Folder
# Attempt to list the directory My Empty Folder to confirm it has been removed
$ ls -d "My Empty Folder"
ls: cannot access 'My Empty Folder': No such file or directory
Explanation: Quoting ("My Empty Folder"
) or escaping (My\ Empty\ Folder
) ensures the shell interprets the name correctly.
6.3. Permissions
To remove a directory target_dir
inside parent_dir
, you need:
- Write (w) permission on
parent_dir
to modify its contents (i.e., removetarget_dir
). - Execute (x) permission on
parent_dir
to access its contents (to check iftarget_dir
is empty).
You generally do not need permissions on target_dir
itself.
Example (Permission Denied):
# Create a directory named restricted
$ mkdir restricted
# Create an empty directory named empty_dir inside restricted
$ mkdir restricted/empty_dir
# Set permissions on restricted to read and execute only (555), removing write permission
$ chmod 555 restricted
# Attempt to remove restricted/empty_dir, which should fail due to lack of write permission on restricted
$ rmdir restricted/empty_dir
rmdir: failed to remove 'restricted/empty_dir': Permission denied
Explanation: The restricted
directory has read and execute permissions (555
), but no write permission, so rmdir
cannot remove empty_dir
. Use sudo
or change permissions (chmod u+w restricted
) to resolve.
6.4. Symbolic Links
If you run rmdir
on a symbolic link that points to a directory, on Linux it will always fail, because rmdir
does not follow directory symlinks. To remove the link itself, use rm
(or unlink
).
# Create an empty directory named actual_empty_dir
$ mkdir actual_empty_dir
# Create a symbolic link named link_to_empty_dir pointing to actual_empty_dir
$ ln -s actual_empty_dir link_to_empty_dir
# Attempt to remove the symbolic link link_to_empty_dir with rmdir, which fails because it’s not a directory
$ rmdir link_to_empty_dir
rmdir: failed to remove 'link_to_empty_dir': Not a directory
# Attempt to remove the symbolic link link_to_empty_dir with a trailing slash, which also fails
$ rmdir link_to_empty_dir/
rmdir: failed to remove 'link_to_empty_dir/': Symbolic link not followed
# Attempt to remove the symbolic link link_to_empty_dir with @ suffix, which fails due to invalid syntax
$ rmdir link_to_empty_dir@
rmdir: failed to remove 'link_to_empty_dir@': No such file or directory
# List the contents with long format to show that the symbolic link and actual directory still exist
$ ls -l
drwxrwxr-x 2 user user 4096 May 12 15:05 actual_empty_dir
lrwxrwxrwx 1 user user 16 May 12 14:32 link_to_empty_dir -> actual_empty_dir
Explanation
-
rmdir link_to_empty_dir
andrmdir link_to_empty_dir/
both error out on Linux becausermdir
refuses to dereference a symlink to a directory. -
To delete the symbolic link only, use:
# Remove the symbolic link named link_to_empty_dir $ rm link_to_empty_dir # OR # Remove the symbolic link named link_to_empty_dir using an alternative command $ unlink link_to_empty_dir
-
To delete the target directory (if empty), refer to it by name:
# Remove the actual directory named actual_empty_dir if it is empty $ rmdir actual_empty_dir
6.5. Mount Points
You cannot remove a directory that is a mount point for another filesystem, even if it appears empty.
# Attempt to remove the directory /mnt/test, which fails if it is a mount point in use
$ rmdir /mnt/test
rmdir: failed to remove '/mnt/test': Device or resource busy
Explanation: You must unmount the filesystem first using umount /mnt/test
before rmdir
can remove the directory.
7. Frequently Asked Questions (FAQ)
Below are answers to common questions about the rmdir
command, based on typical user issues and forum discussions.
7.1. What is the main purpose of the rmdir
command?
The rmdir
command removes empty directories, ensuring no files or subdirectories are deleted, which helps maintain a clean file system safely.
7.2. How is rmdir
different from rm -r
?
rmdir
only removes empty directories, while rm -r
removes directories and their contents recursively. rmdir
is safer for empty directories.
7.3. Why did rmdir my_directory
fail?
The most common reason is that my_directory
is not empty. Check contents with:
# List all contents of my_directory, including hidden files, to check if it is empty
$ ls -A my_directory
Other reasons include insufficient permissions or the directory being a mount point.
7.4. How can I remove a directory and all its contents?
Use rm -r directory_name
. Be cautious, as this deletes everything inside:
# Remove the directory non_empty_dir and all its contents recursively
$ rm -r non_empty_dir
7.5. Can rmdir
remove hidden files inside a directory?
No, rmdir
does not delete files. If a directory contains hidden files (e.g., .hidden
), it’s considered non-empty. Remove hidden files first:
# Remove a hidden file named .hidden inside the directory dir
$ rm dir/.hidden
# Remove the directory dir, which is now empty after removing the hidden file
$ rmdir dir
7.6. What does the -p
option do?
It removes the specified directory and its parent directories if they become empty:
# Remove the directory c and its parent directories b and a if they become empty using the -p option
$ rmdir -p a/b/c
7.7. Is rmdir
safer than rm -r
?
Yes, rmdir
only removes empty directories, preventing accidental data loss.
7.8. Can I use wildcards with rmdir
?
Yes, the shell expands wildcards:
# Remove all directories starting with empty_ that are empty using a wildcard
$ rmdir empty_*
7.9. Does rmdir
follow symbolic links?
rmdir
attempts to remove the target directory of a symbolic link (if empty), not the link itself. To remove the link:
# Remove the symbolic link named symlink_name
$ rm symlink_name
7.10. What happens if I try rmdir
on a file?
It fails with an error:
# Attempt to remove a file named file.txt with rmdir, which fails because it’s not a directory
$ rmdir file.txt
rmdir: failed to remove 'file.txt': Not a directory
7.11. How do I check if a directory is empty before using rmdir
?
Use ls -A
:
# List all contents of directory_name, including hidden files, to check if it is empty
$ ls -A directory_name
If no output is produced, the directory is empty.
7.12. Why does rmdir
fail with “Permission denied”?
You lack write or execute permissions on the parent directory. Check with:
# List the directory parent_dir in long format to display its permissions
$ ls -ld parent_dir
Fix with:
# Add write and execute permissions for the user on the parent_dir directory
$ chmod u+wx parent_dir
7.13. Can rmdir
remove directories recursively?
No, rmdir
only removes empty directories. Use rm -r
for recursive removal.
7.14. How do I handle directories with spaces?
Quote or escape the name:
# Remove the directory named Dir With Spaces using quotes to handle the spaces
$ rmdir "Dir With Spaces"
7.15. Why can’t I remove a mount point with rmdir
?
It’s in use by the filesystem. Unmount first:
# Unmount the filesystem mounted at /mnt/mount_point
$ umount /mnt/mount_point
# Remove the directory /mnt/mount_point if it is empty after unmounting
$ rmdir /mnt/mount_point
7.16. Can rmdir
be used in scripts?
Yes, especially with --ignore-fail-on-non-empty
:
# Attempt to remove the directory dir, ignoring failure if it is non-empty
$ rmdir --ignore-fail-on-non-empty dir
7.17. How do I verify a directory was removed?
Use ls -d
:
# Attempt to list the directory directory_name; an error indicates it has been removed
$ ls -d directory_name
ls: cannot access 'directory_name': No such file or directory
7.18. What if rmdir
says “Directory not found”?
The directory doesn’t exist or the path is incorrect. Verify with:
# List the directory directory_name to check if it exists
$ ls -d directory_name
7.19. Can rmdir
remove multiple directories with one command?
Yes:
# Remove multiple empty directories named dir1, dir2, and dir3 in a single command
$ rmdir dir1 dir2 dir3
7.20. Is there a way to force rmdir
to remove non-empty directories?
No, use rm -r
instead.
8. Conclusion
The rmdir
command is a simple, safe, and effective tool for removing empty directories in Linux. Its key feature is its refusal to delete non-empty directories, which helps prevent accidental data loss. The -p
option is particularly useful for cleaning up entire chains of empty nested directories. While rm -r
is available for removing directories with content, rmdir
should be your first choice when you intend to remove a directory that you believe (or want to ensure) is empty.
9. rmdir
Command: Reference Table of Key Options
Option(s) | Description | Example Command | Use Case |
---|---|---|---|
(none) | Remove specified empty directory(ies) | rmdir my_empty_dir | Basic removal of an empty directory |
-p, --parents | Remove DIRECTORY and its parents if they become empty | rmdir -p a/b/c | Clean up nested empty directory structures |
-v, --verbose | Output a message for every directory processed | rmdir -v empty1 empty2 | Get confirmation of which directories are being removed |
--ignore-fail-on-non-empty | Do not report an error if a directory fails due to being non-empty | rmdir --ignore-fail-on-non-empty mydir | Useful in scripts to attempt removal without erroring on non-empty |
--help | Display help text and exit | rmdir --help | Get quick usage information |
--version | Output version information and exit | rmdir --version | Check the version of the rmdir utility |