rmdir Command in Linux (With Examples)

Last updated Tuesday, February 3, 2026 12:00 pm Joshua James 11 min read

The rmdir command in Linux is a straightforward tool for removing empty directories from the filesystem. It serves one purpose and does it safely: deleting directories that don’t contain any files. This targeted approach helps you maintain a clean directory structure without risking accidental data loss, since rmdir refuses to delete directories that contain anything.

This guide demonstrates how to use rmdir effectively through command-line examples. We’ll cover the essential options, practical scenarios you’ll encounter in daily system administration, and advanced techniques for combining rmdir with other commands. You’ll learn when to use rmdir versus alternatives like rm, how to handle common errors, and how to integrate it into shell scripts for automated cleanup tasks.

Understand the rmdir Command

What is the rmdir Command?

The rmdir command removes empty directories from your Linux filesystem. Think of it as the safe deletion tool because it only works on directories that contain absolutely nothing (no files, no subdirectories, not even hidden files). This built-in safety makes it ideal for cleanup tasks where you want to remove leftover directory structures without worrying about accidentally deleting important data.

Why Use the rmdir Command?

There are several practical reasons to use the rmdir command:

  • Clean Filesystem: Removing leftover empty directories keeps your filesystem organized, especially after uninstalling applications or reorganizing project structures.
  • Safe Deletion: Unlike rm -r, rmdir refuses to delete directories containing files, preventing accidental data loss when cleaning up.
  • Script Automation: The command integrates cleanly into shell scripts for automated cleanup tasks, with predictable behavior and exit codes.
  • Quick Verification: When a directory should be empty but you’re not sure, rmdir provides instant feedback without risking file deletion.

Basic Syntax of the rmdir Command

The basic syntax for the rmdir command is as follows:

rmdir [OPTION]... DIRECTORY...

The command works by specifying options (if any) followed by one or more directory names. At its simplest, rmdir emptydir removes the directory emptydir from your current location, but only if it contains absolutely nothing.

  • rmdir: The command that removes empty directories.
  • [OPTION]…: Optional flags such as -p or -v that adjust how rmdir works.
  • DIRECTORY…: One or more directory paths that must already be empty.

If you are just getting started, picture rmdir as the “empty bin” button. Run rmdir emptydir and it deletes the directory only when nothing remains inside, which keeps you from removing the wrong data.

Common rmdir Options

Here are the most useful options organized by task:

TaskOptionWhat It Does
Get confirmation feedback-v, --verboseDisplays each directory as it’s removed
Remove parent directories-p, --parentsRemoves parent directories if they become empty after child removal
Skip non-empty silently--ignore-fail-on-non-emptyContinues without errors when directory has contents
View all options--helpShows complete syntax and option descriptions
Check version--versionDisplays rmdir version information

The verbose option is particularly helpful in scripts when you want confirmation that directories were actually removed, while --ignore-fail-on-non-empty prevents cleanup scripts from halting when they encounter directories that still contain files.

Installation and Availability

The rmdir command is part of GNU coreutils and comes pre-installed on all Linux distributions. You can verify it exists on your system with:

which rmdir

Expected output:

/usr/bin/rmdir

This confirms the path to the rmdir binary. On older systems, you may see /bin/rmdir instead. Since rmdir is part of GNU coreutils, you will never need to install it separately.

Getting Help and Version Information

Before diving into examples, you can view all available options with:

rmdir --help

This displays the command syntax and all supported options:

Usage: rmdir [OPTION]... DIRECTORY...
Remove the DIRECTORY(ies), if they are empty.

      --ignore-fail-on-non-empty
                    ignore each failure to remove a non-empty directory
  -p, --parents     remove DIRECTORY and its ancestors;
                    e.g., 'rmdir -p a/b' is similar to 'rmdir a/b a'

  -v, --verbose     output a diagnostic for every directory processed
      --help        display this help and exit
      --version     output version information and exit

To check which version of rmdir you are running:

rmdir --version

Expected output:

rmdir (GNU coreutils) 9.4
Copyright (C) 2023 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

The version number varies by distribution. Ubuntu 24.04 ships coreutils 9.4, while older distributions may have earlier versions. All modern versions support the same core options.

Practical Examples of Using the rmdir Command

Example 1: Remove a Single Directory

To remove an empty directory named “sampleDir“:

rmdir sampleDir

This command will only work if “sampleDir” is empty. If there are any files or subdirectories inside it, the command will throw an error. Remember that “empty” means absolutely nothing inside, including hidden files that start with a dot (like .config or .cache). Use ls -la sampleDir to verify a directory is truly empty before attempting removal.

Example 2: Remove Several Directories at Once

To delete multiple empty directories at once, specify all their names:

rmdir dir1 dir2 dir3

All specified directories must be empty for full success. If any directory contains files, rmdir reports an error for that directory but continues processing the others. For example, if dir2 contains a file:

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

In this case, dir1 and dir3 are removed successfully while dir2 remains.

Example 3: Remove Empty Directories Recursively

While rmdir itself does not support recursive removal, you can combine it with the find command to target empty directories safely.

Always preview which directories will be affected before running deletion commands. The find command can match many directories at once, so a dry run with -print helps you verify the results before committing to removal.

First, preview the directories that would be removed:

find . -mindepth 1 -type d -empty -print

Review the list carefully. Once you are comfortable with it, add -depth and replace -print with -exec rmdir {} + to perform the actual removal:

find . -depth -mindepth 1 -type d -empty -exec rmdir {} +

The -depth flag processes directories bottom-up, ensuring parent directories are checked after their children are removed. The -mindepth 1 flag keeps find from removing the current working directory, and using -print first gives you a dry run. Note that BusyBox find on minimal systems may lack -delete, so -exec rmdir {} + offers broader compatibility.

Example 4: Confirm Removals with Verbose Output

To receive a confirmation message for every directory removed:

rmdir -v dirName

Expected output:

rmdir: removing directory, 'dirName'

This confirmation appears only when the directory is successfully removed. The verbose flag is particularly useful in scripts or when processing multiple directories, so you can track exactly what was deleted.

Example 5: Skip Non-Empty Directories

If you are unsure whether a directory is empty and want to skip it silently if not, use the --ignore-fail-on-non-empty option:

rmdir --ignore-fail-on-non-empty dirName

This option suppresses the error message when a directory contains files. The directory remains untouched, but no error appears. This is helpful in automated scripts where you want to attempt cleanup on multiple directories without halting execution when some are not empty.

You can combine this with verbose mode to see which directories were actually removed:

rmdir -v --ignore-fail-on-non-empty dir1 dir2 dir3

Only successfully removed directories produce output, making it easy to track what changed.

Example 6: Remove Empty Parent Directories

To remove a directory and its parent directories in one command, use the -p option:

rmdir -p sampleDir/subDir/

This removes subDir first, then removes sampleDir if it becomes empty. Combine with -v to see each step:

rmdir -pv sampleDir/subDir/

Expected output:

rmdir: removing directory, 'sampleDir/subDir/'
rmdir: removing directory, 'sampleDir'

The command processes from deepest to shallowest, removing each parent only if it becomes empty after the child is deleted. If any parent contains other files or directories, the chain stops at that point. When you need to recreate the structure, our mkdir command guide walks through building directories with the right permissions.

Advanced Uses of the rmdir Command

Example 7: Clean Directory Trees with find

When you need to clean an entire project or shared storage tree, the find command pairs perfectly with rmdir to locate and remove every empty directory.

This operation can remove many directories at once. Always run the preview command first and review the output carefully before executing the actual removal.

Preview what will be deleted:

find /path/to/search -depth -mindepth 1 -type d -empty -print

Review the list carefully. If everything looks correct, replace -print with -exec rmdir {} + to perform the actual removal:

find /path/to/search -depth -mindepth 1 -type d -empty -exec rmdir {} +

Here is what each part does:

  • find: Searches for filesystem objects
  • -depth: Processes directories bottom-up, so parents are checked after their children are removed
  • -mindepth 1: Keeps the search root intact (prevents deleting the starting directory)
  • -type d: Limits results to directories only
  • -empty: Matches only empty directories
  • -exec rmdir {} +: Runs rmdir on each match; the {} placeholder represents each directory and + batches multiple into fewer calls for efficiency

Example 8: Remove Directories with Spaces

If a directory name contains spaces, enclose it in quotes to prevent the shell from treating each word as a separate argument:

rmdir "Directory Name With Spaces"

Without quotes, the shell interprets this as three separate directories: Directory, Name, With, and Spaces. You can also use single quotes or escape each space with a backslash:

rmdir 'Directory Name With Spaces'
rmdir Directory\ Name\ With\ Spaces

Tab completion in most shells handles this automatically by escaping spaces as you type.

Example 9: How rmdir Handles Symbolic Links

The rmdir command treats symbolic links to directories as files, not as directories. If you try to remove a symlink using rmdir, you’ll get an error:

rmdir link_to_dir

The terminal responds with the following error message:

rmdir: failed to remove 'link_to_dir': Not a directory

To remove symbolic links, use the rm or unlink command instead. This behavior is actually a safety feature because rmdir only affects actual directories, preventing accidental removal of links that might point to important locations.

Example 10: Remove Pattern-Matched Directories

To remove directories that match a specific pattern, you can use shell wildcards (globbing patterns):

rmdir temp_*

This removes all empty directories starting with temp_. Common wildcards include * (matches any characters) and ? (matches a single character). For example, rmdir test_dir? matches test_dir1 and test_dira but not test_dir10.

For more complex pattern matching across subdirectories, combine find with rmdir:

find /path/to/parent -maxdepth 1 -type d -name 'temp_*' -empty -exec rmdir {} +

This command removes empty directories that match the pattern while leaving non-empty matches untouched. Quotes around the pattern prevent the shell from expanding it before find runs, ensuring the pattern reaches find intact.

Example 11: Remove Directories from a List

If you have a list of directory paths in a file (one per line), you can remove all that are empty:

while IFS= read -r dir; do
  rmdir "$dir" 2>/dev/null
done < list.txt

The IFS= setting and -r flag preserve spaces and backslashes in directory names. Redirecting errors to /dev/null suppresses messages for directories that are not empty. For better visibility, add verbose output:

while IFS= read -r dir; do
  rmdir -v "$dir" 2>/dev/null
done < list.txt

This shows only the directories that were successfully removed.

Example 12: Integrate rmdir into Cleanup Scripts

The rmdir command integrates cleanly into shell scripts for automated directory cleanup. Here’s a practical example that moves files and then removes the source directory:

#!/bin/bash
# Simple cleanup script that moves files and removes empty source directory

# Move all visible files to new location (note: this skips hidden dotfiles)
mv /path/to/source/* /new/destination/ 2>/dev/null

# Remove the directory if it's now empty
if rmdir /path/to/source/ 2>/dev/null; then
  echo "Successfully cleaned up source directory"
else
  echo "Warning: Source directory not empty, skipped removal"
fi

This script attempts to move all visible files, then uses rmdir to remove the source directory only if it’s empty. Note that /path/to/source/* doesn’t match hidden files (those starting with a dot), so any dotfiles left behind will prevent rmdir from succeeding. The conditional check around rmdir provides graceful failure handling instead of crashing the script when the directory still contains files.

For cleanup scripts that need to verify success, check the exit code:

if rmdir "$directory" 2>/dev/null; then
  echo "Removed: $directory"
else
  echo "Skipped (not empty): $directory"
fi

The exit code is 0 on success and non-zero on failure, making it easy to branch your script logic based on whether the directory was actually removed.

Common Errors and Troubleshooting

While rmdir is straightforward, you might encounter errors. Here’s how to handle common issues:

Directory Not Empty Error

The most common error is trying to remove a directory that contains files or subdirectories:

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

Solution: Check what is inside the directory, including hidden files:

ls -la directory

Hidden files (those starting with a dot, like .config or .gitkeep) are easy to miss with a simple ls. The -a flag reveals everything. If the directory contains files you want to remove, use rm -r directory instead. For safety, rmdir only removes truly empty directories to prevent accidental data loss.

Permission Denied

If you lack permissions to remove a directory:

rmdir: failed to remove 'directory': Permission denied

Solution: Check ownership and permissions on both the directory and its parent:

ls -ld directory
ls -ld .

To remove a subdirectory, you need write and execute permission on the parent directory. If the directory was created with sudo or belongs to another user, use sudo rmdir directory. For directories you should own, change ownership first:

sudo chown $USER directory
rmdir directory

When the directory contains files and requires elevated permissions, use sudo rm -r directory. Reserve the -f flag for situations where you fully understand that it suppresses confirmation prompts and warnings.

Directory Not Found

When the specified directory does not exist:

rmdir: failed to remove 'directory': No such file or directory

Solution: Verify the path exists and check for typos:

ls -d directory
pwd

If the directory name contains special characters, try using tab completion. If ls -d also fails, the directory genuinely does not exist at that path. Use absolute paths (starting with /) if you are unsure about your current location.

rmdir vs rm Command: When to Use Which

Both rmdir and rm can remove directories, but they serve different purposes:

CommandWhat It DoesBest Use Case
rmdirRemoves only empty directories; fails safely otherwiseCleanup tasks, build artifacts, safe directory removal
rm -rRemoves directories and all contents recursivelyDeleting entire directory trees when you are certain
rm -dRemoves empty directories (like rmdir)When you prefer rm syntax but want empty-only behavior

In practice, start with rmdir whenever you think a directory is empty. If it fails with a “Directory not empty” error, investigate what is inside before deciding whether rm -r is appropriate. This workflow prevents the common mistake of running rm -rf on the wrong directory.

The rm -d option exists but lacks rmdir’s focused features like -p for parent removal and clear verbose messaging. Many administrators prefer rmdir because its behavior makes it immediately obvious when a directory was not removed.

Conclusion

The rmdir command safely removes empty directories, preventing accidental data loss during cleanup tasks. Use -p to remove parent directories in one command, -v for confirmation in scripts, and --ignore-fail-on-non-empty for batch operations. Combine with find to clean entire directory trees. For related operations, see our guides on the mv command and chmod command.

Found this guide useful?

Support LinuxCapable to keep tutorials free and up to date.

Buy me a coffee Buy me a coffee

Before commenting, please review our Comments Policy.
Formatting tips for your comment

You can use basic HTML to format your comment. Useful tags currently allowed:

You type Result
<code>command</code> command
<strong>bold</strong> bold
<em>italic</em> italic
<a href="URL">link</a> link
<blockquote>quote</blockquote> quote block

Leave a Comment

We read and reply to every comment - let us know how we can help or improve this guide.

Let us know you are human: