Bash rmdir Command – Delete Files And Directories

Hey there, fellow Linux enthusiast!

After a long project, your file system can start to look like a digital junk drawer. You have got empty folders left behind from old experiments or finished tasks. How do you neatly clear them out? Enter the rmdir command!

rmdir is a specialized Bash command specifically designed for removing directories, but with a crucial catch: it only removes empty ones. This immediately highlights its difference from rm -r (which can delete non-empty directories and files recursively). We will dive into this distinction more, but for now, think of rmdir as a safer, more precise tool for specific cleanup tasks.

This guide is for anyone new to Linux, those learning shell scripting, or users looking to streamline their file management. Let us get your digital workspace tidy!

What is rmdir?

rmdir is the abbreviation for “remove directory.” It is a standard command-line utility in Unix-like operating systems, including Linux. Its core function is to delete one or more existing directories from the file system.

The critical point to remember is its built-in safety net: rmdir will only remove a directory if it contains no files or subdirectories whatsoever. If there is even a single hidden file, rmdir will politely refuse to delete the directory, preventing accidental data loss.

Basic Usage of rmdir

Let us look at the most common ways to use rmdir.

Removing a Single Empty Directory in the Current Location

This is the simplest use case.

Command:

rmdir my_old_folder

Explanation: If my_old_folder is completely empty and located in your current working directory, this command will delete it.

Example:

Imagine you are in your Documents folder, and you have an empty folder called temp_notes.

ls -F
# Output might show:
# projects/  temp_notes/  work/

rmdir temp_notes
ls -F
# Output now:
# projects/  work/

Removing Multiple Empty Directories at Once

You can tackle several empty folders in one go.

Command:

rmdir folder1 folder2 folder3

Explanation: You can remove several empty directories simultaneously by listing their names separated by spaces. All listed directories must be empty for the command to succeed on them.

Example:

ls -F
# Output:
# empty_logs/  old_temp/  report_data/  temp_files/

rmdir empty_logs old_temp temp_files
ls -F
# Output:
# report_data/

Removing an Empty Directory at a Specific Absolute Path

An absolute path starts from the root directory (/) and specifies the exact location, regardless of your current working directory.

Command:

rmdir /home/your_username/downloads/temp_empty_dir

Explanation: This allows you to remove directories from anywhere in your file system by providing their full path from the root.

Example:

Let us say you are in /home/your_username/documents, but you want to remove an empty directory in your downloads.

rmdir /home/your_username/downloads/old_zips

Removing an Empty Directory at a Specific Relative Path

Relative paths are defined in relation to your current working directory. They are often shorter and more convenient when navigating within a project.

Command 1 (sub-directory):

rmdir old_sub_project/empty_cache

Explanation: If old_sub_project exists in your current directory and contains an empty empty_cache folder, this will remove empty_cache.

Command 2 (parent/sibling directory):

rmdir ../sibling_empty_dir

Explanation: The .. represents the parent directory. This command would remove an empty folder (sibling_empty_dir) that is one level up from your current directory, sitting next to it.

Example:

If your current directory is /home/user/project/src, and you want to remove /home/user/project/build/empty_output.

# From /home/user/project/src
rmdir ../build/empty_output

Understanding rmdir Options (Flags)

rmdir has a couple of helpful options, also known as flags, that extend its functionality.

-p (Parents)

This is a powerful option for cleaning up nested empty directories.

Flag: -p or --parents

Explanation: This option allows rmdir to remove a specified directory and any parent directories in the path that become empty as a result of the child directory being removed. It’s fantastic for cleaning up nested structures after you have moved files out.

Example:

Imagine you have the directory structure project/src/main/java. If java is empty, then main becomes empty after java is removed, then src becomes empty, and finally project could become empty if they all contain nothing else.

# Assuming the structure: project/src/main/java (and java is empty)
rmdir -p project/src/main/java

Expected Behavior: If java is removed, and then main is empty, it is removed. If src then becomes empty, it is removed, and so on up to project, if they all become empty in succession. If at any point a parent directory is not empty, the process stops there.

-v (Verbose)

Want to see what rmdir is doing? The verbose flag is your friend.

Flag: -v or --verbose

Explanation: When you use -v, rmdir will print a message for every directory it successfully removes. This is incredibly helpful for confirming what is being deleted, especially when combined with -p for multiple removals.

Example:

rmdir -v empty_logs
# Output:
# rmdir: removing directory 'empty_logs'

# Combining with -p
rmdir -pv temp_data/old_cache
# Expected Output (similar to):
# rmdir: removing directory 'temp_data/old_cache'
# rmdir: removing directory 'temp_data'

Practical rmdir Scenarios and Examples

Let us put rmdir into action with some real-world scenarios.

Scenario 1: Cleaning Up After a Test Run or Build

After testing, you often have empty test_results or build/empty_temp directories.

rmdir test_results
rmdir build/empty_temp

Scenario 2: Removing Multiple, Related Empty Directories

You have just moved all files out of several old project subdirectories.

rmdir old_project/docs old_project/assets

Scenario 3: Removing Nested Empty Directories Efficiently

You have a structure like my_app/old_feature/temp_data/cache/empty_folder, and empty_folder is the only thing inside cache, which is the only thing inside temp_data, etc.

rmdir -p my_app/old_feature/temp_data/cache/empty_folder

Explanation: This command will remove empty_folder, then cache (if it becomes empty), then temp_data (if it becomes empty), and possibly old_feature (if it becomes empty) if they all become empty in succession.

Scenario 4: Removing Dynamically Named Directories

You have created a temporary directory named with today’s date for a backup, and now you want to remove yesterday’s empty backup directory.

rmdir "backup_$(date --date="yesterday" +%Y-%m-%d)"

Explanation: This uses command substitution ($()) to dynamically determine the directory name. The date command inside the parentheses gets executed first, and its output (yesterday’s date in YYYY-MM-DD format) is then used as part of the directory name.

Scenario 5: Handling Directories with Spaces

If your directory names contain spaces, you need to tell the shell to treat the entire name as a single argument.

You have an empty directory named My Old Folder.

Method 1 (Using Quotes – Recommended):

rmdir "My Old Folder"

Explanation: Quotes (") ensure the shell treats the entire name, including spaces, as a single argument. This is generally the safest and clearest method.

Method 2 (Escaping Spaces):

rmdir My\ Old\ Folder

Explanation: The backslash (\) escapes each space, telling the shell to interpret it literally rather than as a delimiter between separate arguments.

Scenario 6: Using ls to Verify Emptiness Before rmdir

This is a crucial step for safety! Before using rmdir, especially if you are unsure, always check if a directory is truly empty.

Workflow:

Check contents:

ls -A my_folder 

The -A flag shows all entries, including hidden ones (like . and .. which represent the directory itself and its parent, respectively, and .DS_Store on macOS). rmdir ignores . and .. but will consider any other hidden files as making the directory non-empty.

Evaluate output: If ls -A shows nothing (except possibly . and ..), then your directory is truly empty from rmdir‘s perspective.

Execute rmdir:

rmdir my_folder

    Explanation: If ls -A returns any output other than just . and .., your directory is not empty and rmdir will fail. This habit prevents frustrating “Directory not empty” errors.

    Scenario 7: When rmdir Fails and What to Do Instead

    Problem: You try to remove a directory that contains files or subdirectories.

    Command:

    rmdir non_empty_folder

    Expected Error:

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

    Solution (Use rm -r with Caution!):

    When a directory is not empty, rmdir is designed to fail. For these situations, you need the more powerful rm -r (remove recursively) command.

    Command:

    rm -r non_empty_folder

    Warning: rm -r is extremely powerful and unforgiving. It will delete everything inside the directory (all files and subdirectories) without warning or confirmation by default. Use it with the utmost care!

    For added safety when using rm -r, consider these options:

    rm -ri: This flag makes rm interactive, prompting you for confirmation before deleting each file or subdirectory within the target.

    rm -ri projects/old_code
    # Example output:
    # remove regular file 'projects/old_code/file1.txt'? y
    # remove directory 'projects/old_code/subfolder'? y

    rm -rI: This flag prompts you once if you are attempting to remove more than three files or if you’re recursively deleting. It’s a good middle ground.

    Avoid rm -rf unless you are absolutely certain of what you are doing and understand the risks. The -f (force) flag bypasses most warnings and prompts.

    Common Pitfalls and Troubleshooting

    Even with simple commands, it is easy to run into common issues. Here is how to troubleshoot rmdir.

    • “Directory not empty” Error:This is the most frequent error with rmdir. It means there are files or subdirectories within the target directory, even if they are hidden. Remember, rmdir’s purpose is to prevent accidental data loss.
      • Solution: Use ls -A to inspect the contents of the directory. If you intend to delete everything, including contents, use rm -r (with extreme caution!) instead of rmdir.
    • “No such file or directory” Error:This indicates that the path or directory name you provided does not exist, or there is a typo.
      • Solution: Double-check your spelling and case sensitivity. Linux file systems are case-sensitive (MyFolder is different from myfolder). Use ls to verify the correct name and path.
    • Permission Denied:If you try to remove a directory in a location where your user does not have the necessary write permissions (e.g., system directories like /var or /usr without sudo), rmdir will fail with “Permission denied.”
      • Solution: You will need appropriate privileges. If you know what you are doing and have the authorization, you might need to prepend sudo to your command (e.g., sudo rmdir /path/to/system/dir). Be extremely careful when using sudo!
    • Tab Completion is Your Friend:Always remember that Tab completion is a powerful feature in the Bash shell. When typing directory names, type the first few letters and press the Tab key. Bash will either complete the name or show you possible completions. This minimizes typos and ensures you are referencing existing paths correctly.
    • Always Verify Contents (Again!):Before executing rmdir on any directory you are unsure about, use ls (especially ls -A) to list its contents. This simple habit can prevent frustration and accidental data retention (or, more dangerously, accidental data loss if you mistakenly use rm -r when you only intended to remove an empty directory).

    And there you have it! The rmdir command is a simple yet powerful tool for keeping your file system organized by safely removing empty directories. By understanding its specific function and its crucial difference from rm -r, you can maintain a tidier and more secure Linux environment.

    FAQ’s – Linux/Unix Bash Command – rmdir


    What is the rmdir command in Bash?
    The rmdir (remove directory) command in Bash is used to delete empty directories from the file system. Unlike rm -r, it only works on directories that contain no files or subdirectories.


    How do I remove an empty directory using rmdir?
    To remove an empty directory named myfolder, use:

    rmdir myfolder

    If the directory is empty, it will be deleted. Otherwise, an error will be shown.


    What happens if I try to delete a non-empty directory with rmdir?
    rmdir will return an error:

    rmdir myfolder

    Output:

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

    To remove a non-empty directory, use:

    rm -r myfolder

    How do I remove multiple directories with rmdir?
    You can list multiple empty directories:

    rmdir dir1 dir2 dir3

    Each directory will be deleted if it is empty.


    How do I remove nested empty directories using rmdir?
    Use the --parents (or -p) option:

    rmdir -p parent/child/grandchild

    This removes grandchild, child, and then parent only if all are empty.


    How can I suppress error messages in rmdir?
    Redirect the standard error to /dev/null:

    rmdir folder 2>/dev/null

    This hides errors like “directory not empty” or “no such file”.


    How do I check if a directory is empty before using rmdir?
    You can check with this command:

    [ -z "$(ls -A myfolder)" ] && rmdir myfolder

    This removes myfolder only if it is empty.


    Can I remove directories with special characters using rmdir?
    Yes, just quote the directory name:

    rmdir "folder with spaces"

    or

    rmdir folder\ with\ spaces

    How do I use rmdir in a Bash script to clean up folders?
    Example script to delete a list of empty directories:

    #!/bin/bash
    for dir in dir1 dir2 dir3; do
      rmdir "$dir" 2>/dev/null || echo "$dir is not empty"
    done

    This attempts to delete each directory and warns if it’s not empty.


    How is rmdir different from rm -r?

    • rmdir: Only deletes empty directories
    • rm -r: Recursively deletes directories and their contents

    Example:

    rmdir empty_folder        # Works only if empty
    rm -r folder_with_files   # Deletes everything inside

    What is the --ignore-fail-on-non-empty option in rmdir?
    This option ignores errors if a directory is not empty:

    rmdir --ignore-fail-on-non-empty folder1 folder2

    It tries to remove each folder but skips any that are not empty, without displaying errors.


    Can I remove symbolic links to directories using rmdir?
    No. rmdir only removes actual directories, not symlinks.

    To remove a symbolic link, use:

    rm symlink_to_folder

    What does the return value of rmdir indicate?

    • 0: Success – directory was removed
    • 1: Failure – directory was not removed (e.g., not empty, doesn’t exist)

    You can check it with:

    rmdir myfolder
    echo $?

    How can I remove only empty directories recursively from a tree?
    Use find with rmdir:

    find . -type d -empty -delete

    This deletes all empty directories starting from the current directory.

    ⚠️ Be cautious — -delete removes them without confirmation.


    Can I use wildcards with rmdir to delete directories?
    Yes, if you are certain the matching directories are empty:

    rmdir testdir*

    This removes all directories starting with testdir, if they are empty.


    Is rmdir available on all Linux/Unix systems?
    Yes. rmdir is part of the GNU coreutils and is available by default in most Linux and Unix distributions, including macOS and Bash on Windows.


    Author

    Debjeet Bhowmik

    Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

    Leave a Comment