Skip to content

Rmdir command linux guide

Command definition

The rmdir command in Linux is used to remove empty directories from the file system. It stands for "remove directory" and will only delete a directory if it is completely empty; if the directory contains files or other directories, the command will fail and return an error message. This command is a straightforward way to clean up your file system by removing unnecessary directories without affecting the contents of the directories.

Usage examples

  1. Remove an empty directory: The primary use of rmdir is to delete directories that do not contain any files or subdirectories. bash rmdir myfolder

  2. Remove multiple empty directories: You can delete multiple empty directories at once by specifying their names in the command. bash rmdir myfolder1 myfolder2

  3. Check for errors: If you try to remove a directory that is not empty, rmdir will return an error message, which can help you check the directory's status. bash rmdir myfolder

  4. Using wildcards: You can use wildcards to remove multiple empty directories that match a certain pattern. bash rmdir myfolder*

  5. Verbose mode: Although rmdir does not have a built-in verbose option, you can combine it with -v in a script to see which directories are being removed. bash rmdir -v myfolder

  6. Scripting directory cleanup: You can use rmdir in scripts to automate the cleanup of empty directories. bash for dir in myfolder*; do rmdir "$dir"; done

  7. Check if a directory is empty: Before using rmdir, you can check if a directory is empty using ls or find. bash ls myfolder

  8. Remove nested empty directories: You can remove nested empty directories, but you must do so one level at a time. bash rmdir myfolder/subfolder

  9. Using -p option (if available): In some systems, rmdir allows you to remove parent directories if they are also empty, using the -p option. bash rmdir -p myfolder/subfolder

  10. Combining with other commands: You can use rmdir in combination with other commands like find to remove empty directories recursively. bash find . -type d -empty -exec rmdir {} \;