The rm and rmdir commands

The rm tool deletes files, and directories if specified. Because it involves data loss by definition, shell script programmers should be very careful with this command:

$ ls
file1  file2  file3
$ rm file1 file2
$ ls
file3

Note that by default, rm does not remove directories:

$ mkdir mydir
$ rm mydir
rm: cannot remove 'mydir': Is a directory

You can force this with the standard -R or -r option, but it's safer to use rmdir. This is because rmdir will refuse to delete a directory if it still has files in it; it only deletes empty directories:

$ mkdir test1 test2
$ touch test1/file test2/file
$ rm -r test1
$ rmdir test2
rmdir: failed to remove 'test2': Directory not empty

We recommend you avoid the -R or -r flag where ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.