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?

  • 2
    Does your rmdir work if there are files in the subdirectory? – Jeff Schaller Jul 2 '17 at 15:54
  • 1
    See also the eponymous system call rmdir(2) which can only remove empty directories. – David Foerster Jul 2 '17 at 20:00
  • 4
    By the way, there's a "correct" procedure for using 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. – ajb Jul 2 '17 at 23:00
  • 3
    @ajb rm -rf ~ /* - clean out my home directory. Or wait, maybe clean out the system. Always good to double check ;). – Tom Carpenter Jul 2 '17 at 23:08
  • 1
    @ajb Notice that rmdir and rm -r are two strings of the same length :-) – Kusalananda Mar 31 '19 at 10:34

rm -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>
  • 17
    Note, that you usually should not use -f if you do not need to. Its handy to use -rf every time, but it disables (almost) all safety checks. – allo Jul 2 '17 at 16:40
  • 5
    -1 for uneccesary recommendation of rm's -f flag which can have unforeseeable, unrevertable consequences – cat Jul 3 '17 at 2:41
  • So rmdir is just rm -d? – Stan Strum Apr 2 '18 at 21:54
  • @StanStrum -d is not a standard option to rm. – Kusalananda Mar 31 '19 at 9:33
  • @cat The 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. – Kusalananda Mar 31 '19 at 9:35

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.