home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Unix Power ToolsUnix Power ToolsSearch this book

14.16. Problems Deleting Directories

What if you want to get rid of a directory? The standard -- and safest -- way to do this is to use the Unix rmdir "remove directory" utility:

% rmdir files

The rmdir command often confuses new users. It will only remove a directory if it is completely empty; otherwise, you'll get an error message:

% rmdir files
rmdir: files: Directory not empty
% ls files
%

As in the example, ls will often show that the directory is empty. What's going on?

It's common for editors and other programs to create " invisible" files (files with names beginning with a dot). The ls command normally doesn't list them; if you want to see them, you have to use ls -A (Section 8.9):[45]

[45]If your version of ls doesn't have the -A option, use -a instead. You'll see the two special directory entries . and .. (Section 8.9), which you can ignore.

% rmdir files
rmdir: files: Directory not empty
% ls -A files
.BAK.textfile2

Here, we see that the directory wasn't empty after all: there's a backup file that was left behind by some editor. You may have used rm * to clean the directory out, but that won't work: rm also ignores files beginning with dots, unless you explicitly tell it to delete them. We really need a wildcard pattern like .??* or .[a-zA-Z0-9]* to catch normal dotfiles without catching the directories . and ..:

% rmdir files
rmdir: files: Directory not empty
% ls -A files
.BAK.textfile2
% rm files/.??*
% rmdir files
%

Other pitfalls might be files whose names consist of nonprinting characters or blank spaces -- sometimes these get created by accident or by malice (yes, some people think this is funny). Such files will usually give you "suspicious" ls output (Section 8.11) (like a blank line).

If you don't want to worry about all these special cases, just use rm -r:

% rm -r files

This command removes the directory and everything that's in it, including other directories. A lot of people warn you about it; it's dangerous because it's easy to delete more than you realize. Personally, I use it all the time, and I've never made a mistake. I never bother with rmdir.

-- ML



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.