Next: , Previous: Archiving, Up: Common Tasks


9.3 Cleaning Up

This section gives examples of removing unwanted files in various situations. Here is a command to remove the CVS backup files created when an update requires a merge:

     find . -name '.#*' -print0 | xargs -0r rm -f

If your find command removes directories, you may find that you get a spurious error message when find tries to recurse into a directory that has now been removed. Using the ‘-depth’ option will normally resolve this problem.

It is also possible to use the ‘-delete’ action:

     find . -depth -name '.#*' -delete

You can run this command to clean out your clutter in /tmp. You might place it in the file your shell runs when you log out (.bash_logout, .logout, or .zlogout, depending on which shell you use).

     find /tmp -depth -user "$LOGNAME" -type f -delete

To remove old Emacs backup and auto-save files, you can use a command like the following. It is especially important in this case to use null-terminated file names because Emacs packages like the VM mailer often create temporary file names with spaces in them, like #reply to David J. MacKenzie<1>#.

     find ~ \( -name '*~' -o -name '#*#' \) -print0 |
       xargs --no-run-if-empty --null rm -vf

Removing old files from /tmp is commonly done from cron:

     find /tmp /var/tmp -depth -not        -type d -mtime +3 -delete
     find /tmp /var/tmp -depth -mindepth 1 -type d -empty    -delete

The second find command above cleans out empty directories depth-first (‘-delete’ implies ‘-depth’ anyway), hoping that the parents become empty and can be removed too. It uses ‘-mindepth’ to avoid removing /tmp itself if it becomes totally empty.

Lastly, an example of a program that almost certainly does not do what the user intended:

     find dirname -delete -name quux

If the user hoped to delete only files named quux they will get an unpleasant surprise; this command will attempt to delete everything at or below the starting point dirname. This is because find evaluates the items on the command line as an expression. The find program will normally execute an action if the preceding action succeeds. Here, there is no action or test before the ‘-delete’ so it will always be executed. The ‘-name quux’ test will be performed for files we successfully deleted, but that test has no effect since ‘-delete’ also disables the default ‘-print’ operation. So the above example will probably delete a lot of files the user didn't want to delete.

This command is also likely to do something you did not intend:

     find dirname -path dirname/foo -prune -o -delete

Because ‘-delete’ turns on ‘-depth’, the ‘-prune’ action has no effect and files in dirname/foo will be deleted too.