rmdir Command in Linux with Examples

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.

Understanding 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.

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

Removing 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 sub-directories inside it, the command will throw an error.

Removing Multiple Directories

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.

Removing 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 . -mindepth 1 -type d -empty -exec rmdir {} +

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.

Displaying 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.

Ignoring 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:

Advertisement
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. When the only issue is a non-empty directory, the exit status is still zero, so follow up with a quick check such as if [ ! -d dirName ] or a conditional rmdir call to confirm the directory actually disappeared.

Removing 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

Combining with Other Commands

The find command pairs perfectly with rmdir to locate and remove all empty directories in a tree:

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

Let’s break down what each part does. The find command searches for filesystem objects, -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 -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.

Handling Spaces in Directory Names

If a directory name has spaces, enclose it in quotes:

rmdir "Directory Name With Spaces"

This ensures the command recognizes the entire directory name.

Behavior with 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
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.

Using Shell Wildcards with rmdir

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.

Removing Empty Directories in 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.

Integrating rmdir into 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
set -euo pipefail
shopt -s dotglob nullglob

# Move all files including hidden ones
entries=(/path/to/source/*)
if ((${#entries[@]})); then
  mv "${entries[@]}" /new/destination/
fi

# Remove the now-empty directory
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 uses set -euo pipefail for strict error handling, dotglob to include hidden files, and nullglob to quietly clear unmatched globs. By storing matches in the entries array, mv runs only when there’s something to move, and the conditional check around rmdir provides graceful failure handling instead of crashing the script.

Advertisement

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 add the -f flag with rm if absolutely necessary, though rmdir itself has no force option.

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. Its simplicity is its strength: it does one thing well and refuses to do anything dangerous.

Key takeaways: use -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. Always verify directory paths before removal, and prefer rmdir over rm -r for empty directories to avoid mistakes.

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.

Leave a Comment