rmdir Command
The rmdir command in Linux is used to remove empty directories from the filesystem. It is a safe command to use for directory removal because it will only delete a directory if it contains no files or subdirectories, thus preventing accidental data loss.
Syntax
Description
If you try to remove a non-empty directory with rmdir, it will return an error. For removing directories that contain files or other subdirectories, you should use the rm -r command. rmdir is often used in scripts where you need to ensure that only truly empty directories are removed.
Common uses include:
- Removing a single empty directory.
- Removing multiple empty directories.
- Removing a directory and its empty parent directories recursively.
Common Options
| Option | Description |
|---|---|
-p, --parents |
Remove DIRECTORY and its ancestors; e.g., 'rmdir -p a/b/c' is like 'rmdir a/b/c a/b a'. |
-v, --verbose |
Output a diagnostic for every directory processed. |
--ignore-fail-on-non-empty |
Ignore failures that are due to non-empty directories. |
Examples
Remove a single empty directory
rmdir my_empty_dir
Creates and then removes an empty directory named my_empty_dir.
Attempt to remove a non-empty directory (will fail)
touch my_dir/file.txt
rmdir my_dir
# Output: rmdir: failed to remove 'my_dir': Directory not empty
Demonstrates that rmdir will not remove a directory containing files.
Remove multiple empty directories
rmdir dir1 dir2 dir3
Removes three empty directories in one command.
Remove parent directories recursively
rmdir -p a/b/c
# This will remove c, then b, then a, if they become empty.
Removes a directory and its parent directories if they become empty after the removal.