Previous Section  < Day Day Up >  Next Section

Recipe 9.14. Deleting Files and Directories

9.14.1 Problem

You have files and directories all over the place. How do you get rid of the ones you don't want?

9.14.2 Solution

Use rm (remove)—with caution! rm will happily delete everything, with no warning.

To delete a single file, with verbose output, use:

$ rm -v games-stats.txt

removed 'game-stats.txt'

To prompt for confirmation first, use:

$ rm -vi dpkglist

rm: remove regular file `dpkglist'? y

removed `dpkglist'

Use the -r (recursive) flag to delete a directory, with all files and subdirectories:

$ rm -rvi /home/games/stats/baseball

That deletes the /baseball directory, and everything in it. To delete /games and everything in it, use:

$ rm -rvi /home/games

You can use shell wildcards to delete groups of files, as in:

$ rm -v *.txt

removed `file4.txt'

removed `file5.txt'

removed `file6.txt'

removed `file7.txt'

Or:

$ rm -v file*

Use the -f (force) flag to make it work, no matter what. This is very dangerous! It will not prompt you, it will simply delete everything in its path:

$ rm -rf /home/games


Be very careful when you're using the -rf flags. rm will happily erase your entire drive.

9.14.3 Discussion

rm -rf / will erase your entire root filesystem. Some folks think it is a funny prank to tell newbies to do this.

Even though the common usage is "rm deletes files," it does not actually delete them, but rather unlinks them from their inodes. A file is not truly deleted until all hard links pointing to it are removed, and it is overwritten. Ordinary users can rm any files in any directories to which they have access, but they can rm only directories that they own.

touch is actually for changing the timestamps on files. Using it to create new empty files is an unintended bonus.

There's also a rmdir command for deleting directories. rmdir won't delete a directory that has something in it. This may make you feel safer, but over time, it will become annoying; lots of programs create files that don't show up in a normal listing (filenames starting with a . are ignored unles you use ls -a). So you'll try to use rmdir and it will tell you that there are still files in the directory. Eventually, you'll just use rm -r.

9.14.4 See Also

  • touch(1), rm(1)

    Previous Section  < Day Day Up >  Next Section