10.6 Deletion: rm and rmdir

10.6.1 rm

rm(1) removes files and directory trees. DOS users will notice the similarity to both the del and deltree commands. rm can be very dangerous if you do not watch yourself. While it is sometimes possible to retrieve a recently deleted file, it can be complicated (and potentially costly) and is beyond the scope of this book.

To remove a single file, specify its name when you run rm:

% rm file1

If the file has write permissions removed, you may get a permission denied error message. To force removal of the file no matter what, pass the -f option, like this:

% rm -f file1

To remove an entire directory, you use the -r and -f options together. This is a good example of how to delete the entire contents of your hard drive. You really don't want to do this. But here's the command anyway:

# rm -rf /

Be very careful with rm; you can shoot yourself in the foot. There are several command line options, which are discussed in detail in the online manual page.

10.6.2 rmdir

rmdir(1) removes directories from the filesystem. The directory must be empty before it can be removed. The syntax is simply:

% rmdir <directory>

This example will remove the hejaz subdirectory in the current working directory:

% rmdir hejaz

If that directory does not exist, rmdir will tell you. You can also specify a full path to a directory to remove, as this example shows:

% rmdir /tmp/hejaz

That example will try to remove the hejaz directory inside the /tmp directory.

You can also remove a directory and all of its parent directories by passing the -p option.

% rmdir -p /tmp/hejaz

This will first try to remove the hejaz directory inside /tmp. If that is successful, it will try to remove /tmp. rmdir will continue this until an error is encountered or the entire tree specified is removed.