Fact-checked by Grok 2 weeks ago

rmdir

rmdir is a command-line utility primarily used in operating systems to remove empty directories from the filesystem, ensuring that only directories without files or subdirectories are deleted to prevent accidental data loss. It corresponds to the standard utility for this purpose, performing actions equivalent to the rmdir() . The command originated in UNIX, where it was introduced as a dedicated tool for directory removal, distinct from the more general rm command which handles files and requires additional options like -r for non-empty directories. In modern implementations, such as coreutils, rmdir supports options including --parents to remove a directory and its ancestors if they become empty, --ignore-fail-on-non-empty to continue processing despite errors on populated directories, and --verbose for diagnostic output. This design emphasizes safety, as attempting to remove a non-empty directory results in an error, unlike rm -r which recursively deletes contents. A functionally similar command exists in Windows Command Prompt as rmdir or its alias rd, which deletes empty directories by default but can remove non-empty ones with the /s parameter, optionally suppressing prompts with /q. In IBM AIX and other Unix variants, rmdir strictly requires the target directory to contain only . and .. entries, aligning with POSIX behavior. Overall, rmdir serves as a precise, low-risk tool for filesystem maintenance across major operating systems.

Overview

Purpose

The rmdir command serves as a for removing empty within hierarchical file systems, enabling users to maintain organized by eliminating unused directory structures without affecting underlying contents. It specifically targets directory entries that contain no files or subdirectories, ensuring that the operation is safe and limited in scope to prevent accidental . If the specified directory is not empty, the command fails, thereby enforcing a deliberate approach to directory . Unlike general file removal tools such as rm, which handle both files and directories with options for recursion, rmdir is designed exclusively for directories and operates non-recursively by default, promoting precision in cleanup tasks. This distinction underscores its role in targeted maintenance rather than broad deletion. For instance, in a software development project, rmdir can conceptually clean up temporary empty folders created during builds, streamlining the directory hierarchy without risking project files.

History

The rmdir command originated in the early days of Unix, appearing in of UNIX released in 1971 as a utility for removing empty directories. At that time, it operated without a dedicated , instead manually verifying that directories were empty, checking permissions, handling special entries like . and .., and unlinking the directory entry. The command's conceptual foundations drew from the operating system, which introduced hierarchical directory structures in the late 1960s, influencing Unix's adoption of a tree-like file organization; however, rmdir was specifically adapted to Unix's inode-based , where directories are treated as special files containing name-to-inode mappings. As Unix evolved, rmdir was incorporated into (BSD) variants and gaining kernel-level support via dedicated system calls in 4.1BSD around 1980, enhancing efficiency in directory management. Standardization came with the POSIX.1-1988 specification (IEEE Std 1003.1-1988), which mandated rmdir's core behavior—removing only empty directories—to promote portability across diverse Unix implementations. In the ecosystem, version of rmdir emerged as part of the initial Fileutils package announced in , later integrated into the unified Core Utilities (coreutils) in the early 1990s, facilitating its integration into and other open-source systems.

Syntax

Basic Syntax

The basic syntax of the rmdir command follows the general form rmdir [options] directory..., where directory denotes one or more pathnames specifying empty directories to remove. This structure allows invocation without mandatory options, focusing solely on the target directories provided as operands. The command processes multiple directory arguments sequentially from left to right, attempting to remove each one if it is empty; failure on one operand does not halt processing of subsequent ones. For nested directories, operands must be ordered such that subdirectories precede parent directories to ensure parents are empty upon removal. rmdir accepts both absolute and relative pathnames for the directory operands. During pathname resolution, intermediate symbolic links are followed to locate the target directory entry. As a standard shell utility, rmdir integrates with shell features like pathname expansion, enabling wildcards (e.g., rmdir dir*) to match and expand to multiple empty directory names before invocation.

Arguments

The rmdir command accepts one or more directory pathnames as operands, referred to as dir in the POSIX specification, where each dir represents the pathname of an empty directory to be removed. These arguments must specify existing directories that contain no entries other than the . and .. subdirectories; otherwise, the command will not remove them and will trigger errors for non-compliant paths. When multiple directory pathnames are provided as arguments, such as rmdir dir1 dir2, the command processes them sequentially in the order specified, attempting to remove each one independently if it meets the emptiness requirement. For successful removal in hierarchical cases without the -p option, child directories must be specified before their parents to ensure parents remain empty at the time of processing. The command resolves directory pathnames according to standard filesystem conventions, supporting both relative paths (interpreted from the current ) and absolute paths (starting from the /). Special restrictions apply to certain pathnames: the / and the current directory . cannot be removed, as they inherently violate the empty directory requirement or lead to unspecified behavior. Additionally, for directories serving as mount points on filesystems, removal fails if the underlying mounted content prevents the directory from being empty.

Implementations

POSIX Compliance

The rmdir utility in POSIX-compliant systems adheres to the specifications outlined in IEEE Std 1003.1-2008, ensuring portability across operating systems. It is required to remove only empty directories—those containing at most the . and .. entries—specified by one or more dir operands, processing them in the order provided. If a directory is non-empty, the utility must fail for that operand without removing it, but continues processing the remaining arguments. Mandatory behaviors include no recursive removal of contents; the utility relies on the underlying rmdir() function, which demands write permission on the directory and search permission on all preceding components of the . Upon successful removal, are preserved, as the operation only deletes the directory entry without altering attributes of the or freeing space beyond the entry itself if the link count reaches zero. The -p option, if supported, allows removal of directories along a pathname after successfully removing a directory, but basic compliance does not mandate this extension. For portability, POSIX mandates standard exit codes: 0 upon successful removal of all specified directories, and a non-zero value if any error occurs, with errno set accordingly for diagnostics. No options beyond the basic syntax are required, promoting without reliance on vendor-specific features. is verified through conformance to IEEE Std 1003.1, with the utility first standardized in .1 in 1988 to facilitate consistent behavior across conforming implementations.

GNU Coreutils Version

The rmdir utility is included in the GNU coreutils package, which originated from the merger of the GNU fileutils, shellutils, and textutils packages and was first released as version 4.5 in September 2002. This implementation has been maintained by the as part of the Project, with primary maintainers including Jim Meyering, Paul Eggert, Pádraig Brady, Bernhard Voelker, and Collin Funk. The default behavior of rmdir in GNU coreutils conforms to requirements for removing empty directories, while incorporating GNU-specific extensions such as the --ignore-fail-on-non-empty and --parents options; it also provides standard GNU information outputs through the --version and --help flags. GNU coreutils supports compilation with internationalization via the library for multi-language message handling and includes feature tests to enable large file support (LFS) for operations on files exceeding 2 GiB, particularly on 32-bit systems. The package, encompassing rmdir, is pre-installed by default on major distributions including and , ensuring widespread availability for system administration tasks. for all versions is hosted on official GNU FTP mirrors for compilation and verification.

Usage

Unix-like Systems

On Unix-like systems, the rmdir command is invoked from a shell such as or Zsh by specifying the to one or more empty directories as arguments. The utility requires search (execute) permission on all parent directories in the to access the target and write permission on the immediate parent directory to remove the directory entry. This aligns with POSIX.1-2008 standards, ensuring portability across compliant systems like , , and macOS. The behavior of rmdir involves attempting to remove each specified directory entry using the rmdir() , which succeeds only if the directory is empty—containing no entries other than the self-referential . and .. directories. The enforces this emptiness requirement atomically during the ; if the directory contains any other entries, the call fails with an error such as ENOTEMPTY, and the utility reports "Directory not empty" without partial removal. Unlike file removal via unlink(), the rmdir() call specifically targets and prevents deletion of non-empty ones to avoid unintended . In scripting contexts, rmdir is commonly integrated for automated cleanup tasks, such as removing temporary directories created with mkdir after processing. For instance, a script might pair it with conditional checks to ensure directories are empty before invocation, and the permissions of newly created directories— influenced by the shell's umask setting—must allow subsequent removal by the user or process. A representative example is rmdir /tmp/emptydir, which succeeds and returns exit code 0 if the directory has no entries beyond . and .., fully removing it from the filesystem. If contents are present, it fails with exit code greater than 0 and the message "rmdir: failed to remove '/tmp/emptydir': not empty."

DOS, Windows, and Derivatives

In and Windows operating systems, the rmdir command, often abbreviated as rd, removes empty directories from the filesystem. Introduced with 2.0 in March 1983, it draws inspiration from Unix origins but adapts to the DOS environment with support for drive letters and case-insensitive path handling on filesystems like and . The command is invoked directly in the Command Prompt (CMD.EXE) or via the rmdir alias in PowerShell, which maps to the Remove-Item cmdlet for broader file system operations. For example, to delete an empty directory on the C: drive, one would use rmdir C:\emptydir or rd C:\emptydir, where paths support backslashes and absolute or relative specifications including drive letters. Unlike strict implementations, Windows versions include a non-standard /s option for recursive deletion of non-empty directories and their contents, though this requires confirmation in interactive sessions to prevent accidental . Without /s, the command checks for subdirectories or files and fails if the target is not empty, ensuring safe operation on vacant directories only. At the system level, rmdir integrates with the Win32 API function RemoveDirectory, which marks the directory for deletion once all handles are closed and confirms emptiness. Derivatives such as and mirror this Windows behavior, providing rmdir and rd with identical syntax, options like /s, and compatibility to maintain interoperability with and Windows applications.

Options

Standard Options

The rmdir command supports the -p option as defined in the standard, with common implementations like Coreutils adding --help and --version for basic functionality. These focus on handling directory hierarchies and providing usage information without altering the core behavior of removing only empty directories. The --help option displays a concise usage summary, including available options and syntax, before exiting with a status (exit code 0). This is a common option in GNU Coreutils utilities, allowing users to quickly command behavior without external documentation. Similarly, the --version option prints the version information of the rmdir utility, such as the GNU Coreutils release number, and exits successfully. It provides essential details for verifying compatibility or , adhering to standard practices in environments. The -p or --parents option enables the removal of parent directories in a specified pathname once child directories are emptied, processing from the innermost to the outermost. For instance, invoking rmdir -p dir1/dir2 first removes dir2 if empty, then dir1 if it becomes empty afterward; this fails if any targeted directory contains non-directory entries. It is part of the standard. In standard usage, options precede directory arguments to align with Utility Syntax Guidelines, ensuring predictable parsing (e.g., rmdir -p dir1/dir2). While some implementations like Coreutils allow flexible option placement, the conventional order maintains compatibility across systems.

Extended Options

In the implementation of rmdir, the --ignore-fail-on-non-empty option allows the command to silently skip that are not empty, ignoring failures solely due to non-emptiness without issuing diagnostics or altering the for those cases. This extension is available in coreutils and is particularly useful when combined with the -p option for removing directory hierarchies, as it enables continuation even if intermediate contain files. GNU coreutils also supports -v or --verbose, which provides a diagnostic message for each successful removal of an empty . Some BSD variants, such as , include a -v (verbose) option that prints a diagnostic message confirming the removal of each empty processed. In Windows Command Prompt, the /s option extends rmdir (also known as rd) to remove a and all its subdirectories, including files, effectively functioning like a recursive deletion tool despite the standard rmdir purpose of handling only empty directories. This deviates from behavior by permitting non-empty directory removal, which can lead to unintended data loss if not used cautiously. These extended options improve usability in specific environments by addressing common workflow needs, such as handling partially populated trees or providing removal confirmations, but they compromise portability across different systems since they are not part of the standard.

Error Conditions

Common Errors

When attempting to remove a directory using the rmdir command, several common errors can occur due to invalid arguments or system constraints. These errors are typically reported as diagnostic messages on , corresponding to underlying failures defined in standards. One frequent issue is the "No such file or directory" error (ENOENT), which arises when the specified does not exist or a component of the is . This occurs if the argument provided to rmdir points to a non-existent location in the filesystem. Another common failure is the "Directory not empty" error (ENOTEMPTY or EEXIST), triggered when the target contains entries other than the standard "." and ".." references, such as files or subdirectories. The rmdir utility requires the directory to be completely empty before removal can proceed. Permission-related errors, such as "Permission denied" (EACCES or EPERM), happen when the user lacks the necessary write permission on the parent directory or search permission on components leading to the target. This also applies if the parent directory has the (S_ISVTX) set and the user is not the owner or . Additionally, the "Not a directory" (ENOTDIR) is encountered if the argument refers to a file or another non-directory object, or if a path component is not a . Invalid paths, such as those exceeding length limits (ENAMETOOLONG), can also lead to similar failures during path resolution.

Exit Codes

The rmdir command provides exit codes to signal the or of directory removal operations, allowing scripts and programs to handle outcomes programmatically. In accordance with the standard, an exit code of 0 indicates successful removal of all specified directories, meaning each referred to an empty that was removed without error. An exit code greater than 0, typically 1 in most implementations, denotes in removing one or more directories, often due to conditions like non-empty directories or permission issues. In the GNU Coreutils implementation, an exit code of 2 is returned for misuse, such as providing invalid options or omitting required arguments. Shell-related invocation errors yield standard codes: 126 when the command is found but cannot be executed due to insufficient permissions, and 127 when the command is not found in the PATH.

References

  1. [1]
    rmdir(1) - Linux manual page - man7.org
    rmdir - remove empty directories. SYNOPSIS top rmdir [OPTION]... DIRECTORY... DESCRIPTION top Remove the DIRECTORY(ies), if they are empty.
  2. [2]
    rmdir - The Open Group Publications Catalog
    The rmdir utility shall remove the directory entry specified by each dir operand. For each dir operand, the rmdir utility shall perform actions equivalent ...
  3. [3]
    rmdir(1) - OpenBSD manual pages
    The rmdir utility is compliant with the IEEE Std 1003.1-2008 (“POSIX.1”) specification. HISTORY. A rmdir command appeared in Version 1 AT&T UNIX.
  4. [4]
    rmdir Command in Linux With Examples - GeeksforGeeks
    Oct 29, 2025 · The rmdir command in Linux is used to safely remove empty directories from the filesystem. Specifically designed to delete only empty ...
  5. [5]
    rmdir | Microsoft Learn
    Feb 3, 2023 · Deletes a directory. The rmdir command can also run from the Windows Recovery Console, using different parameters.
  6. [6]
    Deleting or removing directories (rmdir command) - IBM
    Use the rmdir command to remove the directory, specified by the Directory parameter, from the system. The directory must be empty (it can contain only . and .. ...
  7. [7]
    rmdir Command - IBM
    The rmdir command removes the directory, specified by the Directory parameter, from the system. The directory must be empty before you can remove it.
  8. [8]
    Removing Directories (rmdir)
    To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r .
  9. [9]
    rmdir(1) - NetBSD Manual Pages
    rm(1) STANDARDS The rmdir utility is expected to be IEEE Std 1003.2 (``POSIX.2'') compat- ible. HISTORY An rmdir utility appeared in Version 1 AT&T UNIX.
  10. [10]
  11. [11]
    Chris's Wiki :: blog/unix/UnixDirectoryFiddlingHistory
    Mar 19, 2015 · It took until 4.1 BSD or so for the kernel to take over the work of creating and deleting directories, with real mkdir() and rmdir() system ...
  12. [12]
    [PDF] IEEE standard portable operating system interface for computer ...
    IEEE Std 1003.1-1988 is the first of a group of proposed standards known col¬ loquially, and collectively, as POSIXt. The other POSIX standards are described ...
  13. [13]
    Coreutils - GNU core utilities
    ### Summary of Coreutils History and rmdir Inclusion
  14. [14]
    rmdir
    ### Summary of `rmdir` from https://pubs.opengroup.org/onlinepubs/9699919799/utilities/rmdir.html
  15. [15]
    rmdir
    The POSIX. 1-1990 standard was silent with regard to the behavior of rmdir() when there are multiple hard links to the directory being removed. The requirement ...
  16. [16]
    rmdir invocation (GNU Coreutils 9.9)
    ### Summary of GNU Coreutils `rmdir` (Version 9.9)
  17. [17]
    GNU Core Utilities Frequently Asked Questions
    Welcome to the GNU Core Utilities FAQ. This document answers the most frequently asked questions about the core utilities of the GNU Operating System.
  18. [18]
    GNU gettext utilities
    The GNU gettext utilities are a set of tools that provides a framework within which other free packages may produce multi-lingual messages.
  19. [19]
  20. [20]
    rmdir(2) - Linux manual page - man7.org
    rmdir() deletes a directory, which must be empty. RETURN VALUE top On success, zero is returned. On error, -1 is returned, and errno is set to indicate the ...
  21. [21]
    Microsoft DOS History - Computer Hope
    Dec 9, 2023 · MS-DOS 2.0 was released in March 1983, designed for the IBM PC XT (extended technology). It introduced support for hard disk drives. MS-DOS 2.1 ...
  22. [22]
  23. [23]
    RemoveDirectoryA function (fileapi.h) - Win32 apps - Microsoft Learn
    Nov 19, 2024 · To recursively delete the files in a directory, use the SHFileOperation function. RemoveDirectory can be used to remove a directory junction.
  24. [24]
    Rd and Rmdir Commands - Computer Hope
    Mar 21, 2025 · The rd and rmdir commands remove empty directories in MS-DOS. To delete directories with files or directories within them, you must use the ...
  25. [25]
    sdk/lib/ucrt/filesystem/rmdir.cpp Source File - ReactOS
    6// The _rmdir() function, which removes a directory. 7//. 8#include <corecrt_internal.h>.
  26. [26]
  27. [27]
    rmdir(1)
    ### Options for `rmdir` Command in FreeBSD
  28. [28]
    rmdir
    ERRORS. The rmdir() function will fail if: [EACCES] Search permission is denied on a component of the path prefix, or write permission is denied on the parent ...
  29. [29]
    rmdir() — Remove a directory - IBM
    Removes a directory, pathname, provided that the directory is empty. pathname must not end in . (dot) or .. (dot-dot).
  30. [30]
    Bash command line exit codes demystified - Red Hat
    Feb 4, 2020 · In this article, I explain the handful of reserved error codes, how they can occur, and how to use them to figure out what your problem is.Missing: builtin | Show results with:builtin