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
-por-vthat 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:
| Task | Option | What It Does |
|---|---|---|
| Get confirmation feedback | -v, --verbose | Displays each directory as it’s removed |
| Remove parent directories | -p, --parents | Removes parent directories if they become empty after child removal |
| Skip non-empty silently | --ignore-fail-on-non-empty | Continues without errors when directory has contents |
| View all options | --help | Shows complete syntax and option descriptions |
| Check version | --version | Displays 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
This shows the path to the rmdir binary, typically /usr/bin/rmdir or /bin/rmdir. Since it’s part of the core system utilities, you’ll 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, all supported options, and brief descriptions. To check which version of rmdir you’re running:
rmdir --version
The version information can be useful when troubleshooting or verifying feature availability across different systems.
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, you can specify all their names:
rmdir dir1 dir2 dir3
Again, all specified directories must be empty for the command to execute successfully.
Example 3: Remove Empty Directories Recursively
While rmdir itself doesn’t support recursive removal, you can combine it with the find command to target empty directories safely:
find . -mindepth 1 -type d -empty -print
Run this first to review the directories that will be removed. Once you are comfortable with the list, append -delete or -exec rmdir {} + to remove them:
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
This command will display a message such as rmdir: removing directory, 'dirName' once the directory is deleted.
Example 5: Skip Non-Empty Directories
If you’re unsure whether a directory is empty and don’t want to see an error message, use the --ignore-fail-on-non-empty option:
rmdir --ignore-fail-on-non-empty dirName
This command will silently fail if the directory isn’t empty, which is helpful in scripts where you want to attempt cleanup without halting execution on non-empty directories. The option suppresses error messages but the directory will remain if it contains any files or subdirectories.
Example 6: Remove Empty Parent Directories
To remove parent directories, you can utilize the -p option:
rmdir -p sampleDir/subDir/
This removes subDir and then its parent sampleDir if both are empty. 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:
find /path/to/search -depth -mindepth 1 -type d -empty -exec rmdir {} +
Let’s break down what each part does. The find command 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, -type d limits results to directories, -empty matches only empty ones, and -exec rmdir {} + runs rmdir on each match. The {} placeholder represents each found directory, and + batches multiple directories into fewer rmdir calls for efficiency.
Before running the removal, preview what will be deleted:
find /path/to/search -depth -mindepth 1 -type d -empty -print
This dry run shows exactly which directories match. Review the list, and if everything looks correct, replace -print with -exec rmdir {} +. Keep -mindepth 1 in place so find never deletes the directory you started from.
Example 8: Remove Directories with Spaces
If a directory name has spaces, enclose it in quotes:
rmdir "Directory Name With Spaces"
This ensures the command recognizes the entire directory name.
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 directories in a file and want to remove all that are empty:
while IFS= read -r dir; do
rmdir "$dir"
done < list.txt
This reads each directory from list.txt and removes it while preserving spaces and other special characters.
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: Ensure the directory is truly empty. Use ls -la directory to check contents. If it contains files, use rm -r directory instead. For safety, rmdir only removes 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: First, check ownership and permissions with ls -ld directory. You need write and execute permission on the parent directory (and execute permission on the directory itself) to remove subdirectories. If you have administrative privileges, use sudo rmdir directory. For directories you should own, use sudo chown $USER directory to change ownership, then try again.
Write-protected directories created with sudo require elevated permissions. You can either use sudo rmdir directory or, when the directory still contains files, run sudo rm -r directory to remove it recursively. Reserve -f for situations where you fully understand that it suppresses warnings.
Directory Not Found
When the specified directory doesn’t exist:
rmdir: failed to remove 'directory': No such file or directory
Solution: Verify the path with ls or pwd. Use absolute paths if relative paths fail. Watch for typos in directory names.
rmdir vs rm Command: When to Use Which
Both rmdir and rm can remove directories, but they’re designed for different situations:
- rmdir: Your go-to for safely removing empty directories. It refuses to delete anything that contains files or subdirectories, making it impossible to accidentally wipe out data. Use this when cleaning up project structures, build artifacts, or temporary directories you know should be empty.
- rm -r: Removes directories and everything inside them recursively. This is powerful but dangerous because there’s no undo. Use this only when you’re certain you want to delete entire directory trees, and always double-check the path first.
In practice, start with rmdir whenever you think a directory is empty. If it fails with a “Directory not empty” error, then you can investigate what’s inside and decide whether rm -r is appropriate. This workflow prevents the common mistake of running rm -rf on the wrong directory because you assumed it was empty.
There is also rm -d, which removes empty directories, but it lacks rmdir’s focused options like -p and the helpful messaging in verbose mode. Many administrators keep rmdir in their toolbox specifically because its interface makes it obvious when a directory wasn’t removed.
Conclusion
The rmdir command is the safest tool for removing empty directories in Linux, preventing accidental data loss while keeping your filesystem organized. By using -p to remove parent directories in one command, -v to confirm removals in scripts, and --ignore-fail-on-non-empty when scripting cleanup routines that should continue even if some directories aren’t empty, you can confidently manage directory structures without risking mistakes. Always verify directory paths before removal and prefer rmdir over rm -r for empty directories to maintain that extra layer of safety. For related filesystem operations, check out our guides on the mv command for moving files and directories, or the chmod command for managing permissions that affect directory removal.