I usually delete directories by using rm:
rm -r myDir
However I am aware of another command, rmdir, which seems to do the job just as well:
rmdir myDir
What is the difference between these two commands and when should each be used?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityrm -r
removes a directory and all its contents; rmdir
will only remove a directory if the directory is empty. I like to use the following to remove a directory and all its contents:
rm -rf <directory_to_be_removed>
-f
if you do not need to. Its handy to use -rf
every time, but it disables (almost) all safety checks.
-f
flag which can have unforeseeable, unrevertable consequences
rm
command in general may have these consequences. The -f
flag is useful when running under set -e
in a script. I'd agree that using without thinking is unnecessary.
You should use rm -r
when wanting to recursively remove a directory and all its contents, or when the target may be a directory or file and you want to delete it regardless of what it is.
You should use rmdir
when wanting to remove an empty directory.
The rmdir
command is useful since it refuses to remove non-empty directories and files. This serves as a safety catch in situations where you may want to be absolutely sure that what you're deleting is a directory and that the directory is empty before deleting it (for example in a script) and want to treat it as an error condition otherwise.
rmdir(2)
which can only remove empty directories.rm -r
: (1) Type in the command, but don't enter it (2) Take your hands away from the keyboard (3) Count to five (4) Hit ENTER. I've started doing something like this with all dangerous commands, to give me a chance to look at what I'm doing, make sure I typed things in correctly, think about whether there could be unexpected consequences, etc. Occasionally this leads me to erase my command and do some extra checks first, for example.rm -rf ~ /*
- clean out my home directory. Or wait, maybe clean out the system. Always good to double check ;).rmdir
andrm -r
are two strings of the same length :-)