[Novalug] any clever options on 'rm'

Michael Henry LUG-user@drmikehenry.com
Mon Oct 22 06:38:40 EDT 2007


Mike Shade wrote:
 > Nina,
 >
 > This is where piping commands together really helps.  RM is used for
 > deleting files.  You use 'find' to find files with common criteria.
 >
 > An example:
[...]
 > find. -type f -size -10k | xargs rm -f


Unless you know that the files of interest have no spaces in their 
filenames, you should always use the `-print0` option to `find` and the 
`-0` option to xargs.  This forces the use of the NUL character as a 
separator between filenames.  See the manpages for both tools for 
details.  So the example becomes:

   find . -type f -size -10k -print0 | xargs -0 rm -f

For example, suppose you have three files in a directory:

   $ touch keep
   $ touch no
   $ touch "no keep"
   $ ls | cat
   keep
   no
   no keep

You'd like to delete just the "no keep" file.  You use a `find` command 
to get the list of files to delete (using the `-name` option for an 
example, but it would be `-size` in your case):

   $ find . -name "no keep"
   ./no keep

You verify that `find` is showing the correct file to delete, so you use 
the dangerous invocation:

   $ find . -name "no keep" | xargs rm

But because xargs treats spaces as filename delimiters, it sees the "no 
keep" filename as two totally different filenames ("no" and "keep"), and 
`rm` will delete them instead of deleting "no keep":

   $ ls | cat
   no keep

With the `-print0`/`-0` combination, there are no nasty surprises:

   $ touch keep
   $ touch no
   $ touch "no keep"
   $ ls | cat
   keep
   no
   no keep
   $ find . -name "no keep" -print0 | xargs -0 rm
   $ ls | cat
   keep
   no

Michael Henry



More information about the Novalug mailing list