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
-
Remove an empty directory: The primary use of
rmdir
is to delete directories that do not contain any files or subdirectories.bash rmdir myfolder
-
Remove multiple empty directories: You can delete multiple empty directories at once by specifying their names in the command.
bash rmdir myfolder1 myfolder2
-
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
-
Using wildcards: You can use wildcards to remove multiple empty directories that match a certain pattern.
bash rmdir myfolder*
-
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
-
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
-
Check if a directory is empty: Before using
rmdir
, you can check if a directory is empty usingls
orfind
.bash ls myfolder
-
Remove nested empty directories: You can remove nested empty directories, but you must do so one level at a time.
bash rmdir myfolder/subfolder
-
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
-
Combining with other commands: You can use
rmdir
in combination with other commands likefind
to remove empty directories recursively.bash find . -type d -empty -exec rmdir {} \;