find: Cleaning Up

1 
1 9.3 Cleaning Up
1 ===============
1 
1 This section gives examples of removing unwanted files in various
1 situations.  Here is a command to remove the CVS backup files created
1 when an update requires a merge:
1 
1      find . -name '.#*' -print0 | xargs -0r rm -f
1 
1    If your 'find' command removes directories, you may find that you get
1 a spurious error message when 'find' tries to recurse into a directory
1 that has now been removed.  Using the '-depth' option will normally
1 resolve this problem.
1 
1    It is also possible to use the '-delete' action:
1 
1      find . -depth -name '.#*' -delete
1 
1    You can run this command to clean out your clutter in '/tmp'.  You
1 might place it in the file your shell runs when you log out
1 ('.bash_logout', '.logout', or '.zlogout', depending on which shell you
1 use).
1 
1      find /tmp -depth -user "$LOGNAME" -type f -delete
1 
1    To remove old Emacs backup and auto-save files, you can use a command
1 like the following.  It is especially important in this case to use
1 null-terminated file names because Emacs packages like the VM mailer
1 often create temporary file names with spaces in them, like '#reply to
1 David J. MacKenzie<1>#'.
1 
1      find ~ \( -name '*~' -o -name '#*#' \) -print0 |
1        xargs --no-run-if-empty --null rm -vf
1 
1    Removing old files from '/tmp' is commonly done from 'cron':
1 
1      find /tmp /var/tmp -depth -not        -type d -mtime +3 -delete
1      find /tmp /var/tmp -depth -mindepth 1 -type d -empty    -delete
1 
1    The second 'find' command above cleans out empty directories
1 depth-first ('-delete' implies '-depth' anyway), hoping that the parents
1 become empty and can be removed too.  It uses '-mindepth' to avoid
1 removing '/tmp' itself if it becomes totally empty.
1 
1    Lastly, an example of a program that almost certainly does not do
1 what the user intended:
1 
1      find dirname -delete -name quux
1 
1    If the user hoped to delete only files named 'quux' they will get an
1 unpleasant surprise; this command will attempt to delete everything at
1 or below the starting point 'dirname'.  This is because 'find' evaluates
1 the items on the command line as an expression.  The 'find' program will
1 normally execute an action if the preceding action succeeds.  Here,
1 there is no action or test before the '-delete' so it will always be
1 executed.  The '-name quux' test will be performed for files we
1 successfully deleted, but that test has no effect since '-delete' also
1 disables the default '-print' operation.  So the above example will
1 probably delete a lot of files the user didn't want to delete.
1 
1    This command is also likely to do something you did not intend:
1      find dirname -path dirname/foo -prune -o -delete
1 
1    Because '-delete' turns on '-depth', the '-prune' action has no
1 effect and files in 'dirname/foo' will be deleted too.
1