Prepare for POSIX standardisation of -path.
[findutils.git] / doc / find.texi
bloba9e827c6313cb25d5047644ec611f4b5e992632f
1 \input texinfo @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename find.info
4 @settitle Finding Files
5 @c For double-sided printing, uncomment:
6 @c @setchapternewpage odd
7 @c %**end of header
9 @include version.texi
10 @include ../locate/dblocation.texi
12 @iftex
13 @finalout
14 @end iftex
16 @dircategory Basics
17 @direntry
18 * Finding files: (find).        Operating on files matching certain criteria.
19 @end direntry
21 @dircategory Individual utilities
22 @direntry
23 * find: (find)Invoking find.                    Finding and acting on files.
24 * locate: (find)Invoking locate.                Finding files in a database.
25 * updatedb: (find)Invoking updatedb.            Building the locate database.
26 * xargs: (find)Invoking xargs.                  Operating on many files.
27 @end direntry
29 @copying
31 This file documents the GNU utilities for finding files that match
32 certain criteria and performing various operations on them.
34 Copyright (C) 1994, 1996, 1998, 2000, 2001, 2003, 2004, 2005, 2006,
35 2007 Free Software Foundation, Inc.
37 Permission is granted to make and distribute verbatim copies of
38 this manual provided the copyright notice and this permission notice
39 are preserved on all copies.
41 @ignore
42 Permission is granted to process this file through TeX and print the
43 results, provided the printed document carries copying permission
44 notice identical to this one except for the removal of this paragraph
45 (this paragraph not being relevant to the printed manual).
47 @end ignore
48 Permission is granted to copy and distribute modified versions of this
49 manual under the conditions for verbatim copying, provided that the
50 entire resulting derived work is distributed under the terms of a
51 permission notice identical to this one.
53 Permission is granted to copy and distribute translations of this
54 manual into another language, under the above conditions for modified
55 versions, except that this permission notice may be stated in a
56 translation approved by the Foundation.
57 @end copying
59 @titlepage
60 @title Finding Files
61 @subtitle Edition @value{EDITION}, for GNU @code{find} version @value{VERSION}
62 @subtitle @value{UPDATED}
63 @author by David MacKenzie and James Youngman
65 @page
66 @vskip 0pt plus 1filll
67 @insertcopying{}
68 @end titlepage
70 @contents
72 @ifnottex
73 @node Top
74 @top GNU Findutils
75 @comment  node-name,  next,  previous,  up
77 This file documents the GNU utilities for finding files that match
78 certain criteria and performing various actions on them.
80 This is edition @value{EDITION}, for @code{find} version @value{VERSION}.
81 @end ifnottex
83 @c The master menu, created with texinfo-master-menu, goes here.
85 @menu
86 * Introduction::                Summary of the tasks this manual describes.
87 * Finding Files::               Finding files that match certain criteria.
88 * Actions::                     Doing things to files you have found.
89 * Databases::                   Maintaining file name databases.
90 * File Permissions::            How to control access to files.
91 * Date input formats::          Specifying literal times.
92 * Reference::                   Summary of how to invoke the programs.
93 * Common Tasks::                Solutions to common real-world problems.
94 * Worked Examples::             Examples demonstrating more complex points.
95 * Security Considerations::     Security issues relating to findutils.
96 * Error Messages::              Explanations of some messages you might see.
97 * Primary Index::               The components of @code{find} expressions.
98 @end menu
100 @node Introduction
101 @chapter Introduction
103 This manual shows how to find files that meet criteria you specify,
104 and how to perform various actions on the files that you find.  The
105 principal programs that you use to perform these tasks are
106 @code{find}, @code{locate}, and @code{xargs}.  Some of the examples in
107 this manual use capabilities specific to the GNU versions of those
108 programs.
110 GNU @code{find} was originally written by Eric Decker, with
111 enhancements by David MacKenzie, Jay Plett, and Tim Wood.  GNU
112 @code{xargs} was originally written by Mike Rendell, with enhancements
113 by David MacKenzie.  GNU @code{locate} and its associated utilities
114 were originally written by James Woods, with enhancements by David
115 MacKenzie.  The idea for @samp{find -print0} and @samp{xargs -0} came
116 from Dan Bernstein.  The current maintainer of GNU findutils (and this
117 manual) is James Youngman.  Many other people have contributed bug
118 fixes, small improvements, and helpful suggestions.  Thanks!
120 To report a bug in GNU findutils, please use the form on the Savannah
121 web site at
122 @code{http://savannah.gnu.org/bugs/?group=findutils}.  Reporting bugs
123 this way means that you will then be able to track progress in fixing
124 the problem.  
126 If you don't have web access, you can also just send mail to the
127 mailing list.  The mailing list @email{bug-findutils@@gnu.org} carries
128 discussion of bugs in findutils, questions and answers about the
129 software and discussion of the development of the programs.  To join
130 the list, send email to @email{bug-findutils-request@@gnu.org}.
132 Please read any relevant sections of this manual before asking for
133 help on the mailing list.  You may also find it helpful to read the
134 NON-BUGS section of the @code{find} manual page.
136 If you ask for help on the mailing list, people will be able to help
137 you much more effectively if you include the following things:
139 @itemize @bullet
140 @item The version of the software you are running.  You can find this
141 out by running @samp{locate --version}.
142 @item What you were trying to do
143 @item The @emph{exact} command line you used
144 @item The @emph{exact} output you got (if this is very long, try to
145 find a smaller example which exhibits the same problem)
146 @item The output you expected to get
147 @end itemize
149 It may also be the case that the bug you are describing has already
150 been fixed, if it is a bug.  Please check the most recent findutils
151 releases at @url{ftp://ftp.gnu.org/gnu/findutils} and, if possible,
152 the development branch at @url{ftp://alpha.gnu.org/gnu/findutils}.
153 If you take the time to check that your bug still exists in current
154 releases, this will greatly help people who want to help you solve
155 your problem.  Please also be aware that if you obtained findutils as
156 part of the GNU/Linux 'distribution', the distributions often lag
157 seriously behind findutils releases, even the stable release.  Please
158 check the GNU FTP site.
160 @menu
161 * Scope::
162 * Overview::
163 * find Expressions::
164 @end menu
166 @node Scope
167 @section Scope
169 For brevity, the word @dfn{file} in this manual means a regular file,
170 a directory, a symbolic link, or any other kind of node that has a
171 directory entry.  A directory entry is also called a @dfn{file name}.
172 A file name may contain some, all, or none of the directories in a
173 path that leads to the file.  These are all examples of what this
174 manual calls ``file names'':
176 @example
177 parser.c
178 README
179 ./budget/may-94.sc
180 fred/.cshrc
181 /usr/local/include/termcap.h
182 @end example
184 A @dfn{directory tree} is a directory and the files it contains, all
185 of its subdirectories and the files they contain, etc.  It can also be
186 a single non-directory file.
188 These programs enable you to find the files in one or more directory
189 trees that:
191 @itemize @bullet
192 @item
193 have names that contain certain text or match a certain pattern;
194 @item
195 are links to certain files;
196 @item
197 were last used during a certain period of time;
198 @item
199 are within a certain size range;
200 @item
201 are of a certain type (regular file, directory, symbolic link, etc.);
202 @item
203 are owned by a certain user or group;
204 @item
205 have certain access permissions or special mode bits;
206 @item
207 contain text that matches a certain pattern;
208 @item
209 are within a certain depth in the directory tree;
210 @item
211 or some combination of the above.
212 @end itemize
214 Once you have found the files you're looking for (or files that are
215 potentially the ones you're looking for), you can do more to them than
216 simply list their names.  You can get any combination of the files'
217 attributes, or process the files in many ways, either individually or
218 in groups of various sizes.  Actions that you might want to perform on
219 the files you have found include, but are not limited to:
221 @itemize @bullet
222 @item
223 view or edit
224 @item
225 store in an archive
226 @item
227 remove or rename
228 @item
229 change access permissions
230 @item
231 classify into groups
232 @end itemize
234 This manual describes how to perform each of those tasks, and more.
236 @node Overview
237 @section Overview
239 The principal programs used for making lists of files that match given
240 criteria and running commands on them are @code{find}, @code{locate},
241 and @code{xargs}.  An additional command, @code{updatedb}, is used by
242 system administrators to create databases for @code{locate} to use.
244 @code{find} searches for files in a directory hierarchy and prints
245 information about the files it found.  It is run like this:
247 @example
248 find @r{[}@var{file}@dots{}@r{]} @r{[}@var{expression}@r{]}
249 @end example
251 @noindent
252 Here is a typical use of @code{find}.  This example prints the names
253 of all files in the directory tree rooted in @file{/usr/src} whose
254 name ends with @samp{.c} and that are larger than 100 Kilobytes.
255 @example
256 find /usr/src -name '*.c' -size +100k -print
257 @end example
259 Notice that the wildcard must be enclosed in quotes in order to
260 protect it from expansion by the shell.
262 @code{locate} searches special file name databases for file names that
263 match patterns.  The system administrator runs the @code{updatedb}
264 program to create the databases.  @code{locate} is run like this:
266 @example
267 locate @r{[}@var{option}@dots{}@r{]} @var{pattern}@dots{}
268 @end example
270 @noindent
271 This example prints the names of all files in the default file name
272 database whose name ends with @samp{Makefile} or @samp{makefile}.
273 Which file names are stored in the database depends on how the system
274 administrator ran @code{updatedb}.
275 @example
276 locate '*[Mm]akefile'
277 @end example
279 The name @code{xargs}, pronounced EX-args, means ``combine
280 arguments.''  @code{xargs} builds and executes command lines by
281 gathering together arguments it reads on the standard input.  Most
282 often, these arguments are lists of file names generated by
283 @code{find}.  @code{xargs} is run like this:
285 @example
286 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
287 @end example
289 @noindent
290 The following command searches the files listed in the file
291 @file{file-list} and prints all of the lines in them that contain the
292 word @samp{typedef}.
293 @example
294 xargs grep typedef < file-list
295 @end example
297 @node find Expressions
298 @section @code{find} Expressions
300 The expression that @code{find} uses to select files consists of one
301 or more @dfn{primaries}, each of which is a separate command line
302 argument to @code{find}.  @code{find} evaluates the expression each
303 time it processes a file.  An expression can contain any of the
304 following types of primaries:
306 @table @dfn
307 @item options
308 affect overall operation rather than the processing of a specific
309 file;
310 @item tests
311 return a true or false value, depending on the file's attributes;
312 @item actions
313 have side effects and return a true or false value; and
314 @item operators
315 connect the other arguments and affect when and whether they are
316 evaluated.
317 @end table
319 You can omit the operator between two primaries; it defaults to
320 @samp{-and}.  @xref{Combining Primaries With Operators}, for ways to
321 connect primaries into more complex expressions.  If the expression
322 contains no actions other than @samp{-prune}, @samp{-print} is
323 performed on all files for which the entire expression is true
324 (@pxref{Print File Name}).
326 Options take effect immediately, rather than being evaluated for each
327 file when their place in the expression is reached.  Therefore, for
328 clarity, it is best to place them at the beginning of the expression.
329 There are two exceptions to this; @samp{-daystart} and @samp{-follow}
330 have different effects depending on where in the command line they
331 appear.  This can be confusing, so it's best to keep them at the
332 beginning, too.
334 Many of the primaries take arguments, which immediately follow them in
335 the next command line argument to @code{find}.  Some arguments are
336 file names, patterns, or other strings; others are numbers.  Numeric
337 arguments can be specified as
339 @table @code
340 @item +@var{n}
341 for greater than @var{n},
342 @item -@var{n}
343 for less than @var{n},
344 @item @var{n}
345 for exactly @var{n}.
346 @end table
348 @node Finding Files
349 @chapter Finding Files
351 By default, @code{find} prints to the standard output the names of the
352 files that match the given criteria.  @xref{Actions}, for how to get
353 more information about the matching files.
356 @menu
357 * Name::
358 * Links::
359 * Time::
360 * Size::
361 * Type::
362 * Owner::
363 * Mode Bits::
364 * Contents::
365 * Directories::
366 * Filesystems::
367 * Combining Primaries With Operators::
368 @end menu
370 @node Name
371 @section Name
373 Here are ways to search for files whose name matches a certain
374 pattern.  @xref{Shell Pattern Matching}, for a description of the
375 @var{pattern} arguments to these tests.
377 Each of these tests has a case-sensitive version and a
378 case-insensitive version, whose name begins with @samp{i}.  In a
379 case-insensitive comparison, the patterns @samp{fo*} and @samp{F??}
380 match the file names @file{Foo}, @samp{FOO}, @samp{foo}, @samp{fOo},
381 etc.
383 @menu
384 * Base Name Patterns::
385 * Full Name Patterns::
386 * Fast Full Name Search::
387 * Shell Pattern Matching::      Wildcards used by these programs.
388 @end menu
390 @node Base Name Patterns
391 @subsection Base Name Patterns
393 @deffn Test -name pattern
394 @deffnx Test -iname pattern
395 True if the base of the file name (the path with the leading
396 directories removed) matches shell pattern @var{pattern}.  For
397 @samp{-iname}, the match is case-insensitive.@footnote{Because we
398 need to perform case-insensitive matching, the GNU fnmatch
399 implementation is always used; if the C library includes the GNU
400 implementation, we use that and otherwise we use the one from gnulib}
401 To ignore a whole directory tree, use @samp{-prune}
402 (@pxref{Directories}).  As an example, to find Texinfo source files in
403 @file{/usr/local/doc}:
405 @example
406 find /usr/local/doc -name '*.texi'
407 @end example
409 Notice that the wildcard must be enclosed in quotes in order to
410 protect it from expansion by the shell.
412 As of findutils version 4.2.2, patterns for @samp{-name} and
413 @samp{-iname} will match a file name with a leading @samp{.}.  For
414 example the command @samp{find /tmp -name \*bar} will match the file
415 @file{/tmp/.foobar}.  Braces within the pattern (@samp{@{@}}) are not
416 considered to be special (that is, @code{find . -name 'foo@{1,2@}'}
417 matches a file named @file{foo@{1,2@}}, not the files @file{foo1} and
418 @file{foo2}.
419 @end deffn
422 @node Full Name Patterns
423 @subsection Full Name Patterns
425 @deffn Test -path pattern
426 @deffnx Test -wholename pattern
427 True if the entire file name, starting with the command line argument
428 under which the file was found, matches shell pattern @var{pattern}.
429 To ignore a whole directory tree, use @samp{-prune} rather than
430 checking every file in the tree (@pxref{Directories}).  The ``entire
431 file name'' as used by @code{find} starts with the starting-point
432 specified on the command line, and is not converted to an absolute
433 pathname, so for example @code{cd /; find tmp -wholename /tmp} will
434 never match anything.   The name @samp{-wholename} is GNU-specific,
435 but @samp{-path} is more portable; it is supported by HP-UX
436 @code{find} and will soon be part of POSIX.
437 @end deffn
439 @deffn Test -ipath pattern
440 @deffnx Test -iwholename pattern
441 These tests are like @samp{-wholename} and @samp{-path}, but the match
442 is case-insensitive.
443 @end deffn
446 In the context of the tests @samp{-path}, @samp{-wholename},
447 @samp{-ipath} and @samp{-wholename}, a ``full path'' is the name of
448 all the directories traversed from @code{find}'s start point to the
449 file being tested, followed by the base name of the file itself.
450 These paths are often not absolute paths; for example
452 @example
453 $ cd /tmp
454 $ mkdir -p foo/bar/baz
455 $ find foo -path foo/bar -print
456 foo/bar
457 $ find foo -path /tmp/foo/bar -print
458 $ find /tmp/foo -path /tmp/foo/bar -print
459 /tmp/foo/bar
460 @end example
462 Notice that the second @code{find} command prints nothing, even though
463 @file{/tmp/foo/bar} exists and was examined by @code{find}.
467 @deffn Test -regex expr
468 @deffnx Test -iregex expr
469 True if the entire file name matches regular expression @var{expr}.
470 This is a match on the whole path, not a search.  For example, to
471 match a file named @file{./fubar3}, you can use the regular expression
472 @samp{.*bar.} or @samp{.*b.*3}, but not @samp{f.*r3}.  @xref{Regexps,
473 , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}, for a
474 description of the syntax of regular expressions.  For @samp{-iregex},
475 the match is case-insensitive.  There are several varieties of regular
476 expressions; by default this test uses POSIX basic regular
477 expressions, but this can be changed with the option
478 @samp{-regextype}.
479 @end deffn
481 @deffn Option -regextype name
482 This option controls the variety of regular expression syntax
483 understood by the @samp{-regex} and @samp{-iregex} tests.  This option
484 is positional; that is, it only affects regular expressions which
485 occur later in the command line.  If this option is not given, GNU
486 Emacs regular expressions are assumed.  Currently-implemented types
490 @table @samp
491 @item emacs
492 Regular expressions compatible with GNU Emacs; this is also the
493 default behaviour if this option is not used.
494 @item posix-awk
495 Regular expressions compatible with the POSIX awk command (not GNU awk)
496 @item posix-basic
497 POSIX Basic Regular Expressions.
498 @item posix-egrep
499 Regular expressions compatible with the POSIX egrep command
500 @item posix-extended
501 POSIX Extended Regular Expressions
502 @end table
504 @ref{Regular Expressions} for more information on the regular
505 expression dialects understood by GNU findutils.
508 @end deffn
510 @node Fast Full Name Search
511 @subsection Fast Full Name Search
513 To search for files by name without having to actually scan the
514 directories on the disk (which can be slow), you can use the
515 @code{locate} program.  For each shell pattern you give it,
516 @code{locate} searches one or more databases of file names and
517 displays the file names that contain the pattern.  @xref{Shell Pattern
518 Matching}, for details about shell patterns.
520 If a pattern is a plain string---it contains no
521 metacharacters---@code{locate} displays all file names in the database
522 that contain that string.  If a pattern contains
523 metacharacters, @code{locate} only displays file names that match the
524 pattern exactly.  As a result, patterns that contain metacharacters
525 should usually begin with a @samp{*}, and will most often end with one
526 as well.  The exceptions are patterns that are intended to explicitly
527 match the beginning or end of a file name.
529 If you only want @code{locate} to match against the last component of
530 the file names (the ``base name'' of the files) you can use the
531 @samp{--basename} option.  The opposite behaviour is the default, but
532 can be selected explicitly by using the option @samp{--wholename}.
534 The command
535 @example
536 locate @var{pattern}
537 @end example
539 is almost equivalent to
540 @example
541 find @var{directories} -name @var{pattern}
542 @end example
544 where @var{directories} are the directories for which the file name
545 databases contain information.  The differences are that the
546 @code{locate} information might be out of date, and that @code{locate}
547 handles wildcards in the pattern slightly differently than @code{find}
548 (@pxref{Shell Pattern Matching}).
550 The file name databases contain lists of files that were on the system
551 when the databases were last updated.  The system administrator can
552 choose the file name of the default database, the frequency with which
553 the databases are updated, and the directories for which they contain
554 entries.
556 Here is how to select which file name databases @code{locate}
557 searches.  The default is system-dependent.  At the time this document
558 was generated, the default was @file{@value{LOCATE_DB}}.
560 @table @code
561 @item --database=@var{path}
562 @itemx -d @var{path}
563 Instead of searching the default file name database, search the file
564 name databases in @var{path}, which is a colon-separated list of
565 database file names.  You can also use the environment variable
566 @code{LOCATE_PATH} to set the list of database files to search.  The
567 option overrides the environment variable if both are used.
568 @end table
570 GNU @code{locate} can read file name databases generated by the
571 @code{slocate} package.  However, these generally contain a list of
572 all the files on the system, and so when using this database,
573 @code{locate} will produce output only for files which are accessible
574 to you.  @xref{Invoking locate}, for a description of the
575 @samp{--existing} option which is used to do this.
577 The @code{updatedb} program can also generate database in a format
578 compatible with @code{slocate}.  @xref{Invoking updatedb}, for a
579 description of its @samp{--dbformat} and @samp{--output} options.
582 @node Shell Pattern Matching
583 @subsection Shell Pattern Matching
585 @code{find} and @code{locate} can compare file names, or parts of file
586 names, to shell patterns.  A @dfn{shell pattern} is a string that may
587 contain the following special characters, which are known as
588 @dfn{wildcards} or @dfn{metacharacters}.
590 You must quote patterns that contain metacharacters to prevent the
591 shell from expanding them itself.  Double and single quotes both work;
592 so does escaping with a backslash.
594 @table @code
595 @item *
596 Matches any zero or more characters.
598 @item ?
599 Matches any one character.
601 @item [@var{string}]
602 Matches exactly one character that is a member of the string
603 @var{string}.  This is called a @dfn{character class}.  As a
604 shorthand, @var{string} may contain ranges, which consist of two
605 characters with a dash between them.  For example, the class
606 @samp{[a-z0-9_]} matches a lowercase letter, a number, or an
607 underscore.  You can negate a class by placing a @samp{!} or @samp{^}
608 immediately after the opening bracket.  Thus, @samp{[^A-Z@@]} matches
609 any character except an uppercase letter or an at sign.
611 @item \
612 Removes the special meaning of the character that follows it.  This
613 works even in character classes.
614 @end table
616 In the @code{find} tests that do shell pattern matching (@samp{-name},
617 @samp{-wholename}, etc.), wildcards in the pattern will match a
618 @samp{.}  at the beginning of a file name.  This is also the case for
619 @code{locate}.  Thus, @samp{find -name '*macs'} will match a file
620 named @file{.emacs}, as will @samp{locate '*macs'}.
622 Slash characters have no special significance in the shell pattern
623 matching that @code{find} and @code{locate} do, unlike in the shell,
624 in which wildcards do not match them.  Therefore, a pattern
625 @samp{foo*bar} can match a file name @samp{foo3/bar}, and a pattern
626 @samp{./sr*sc} can match a file name @samp{./src/misc}.
628 If you want to locate some files with the @samp{locate} command but
629 don't need to see the full list you can use the @samp{--limit} option
630 to see just a small number of results, or the @samp{--count} option to
631 display only the total number of matches.
633 @node Links
634 @section Links
636 There are two ways that files can be linked together.  @dfn{Symbolic
637 links} are a special type of file whose contents are a portion of the
638 name of another file.  @dfn{Hard links} are multiple directory entries
639 for one file; the file names all have the same index node
640 (@dfn{inode}) number on the disk.
642 @menu
643 * Symbolic Links::
644 * Hard Links::
645 @end menu
647 @node Symbolic Links
648 @subsection Symbolic Links
650 Symbolic links are names that reference other files.  GNU @code{find}
651 will handle symbolic links in one of two ways; firstly, it can
652 dereference the links for you - this means that if it comes across a
653 symbolic link, it examines the file that the link points to, in order
654 to see if it matches the criteria you have specified.  Secondly, it
655 can check the link itself in case you might be looking for the actual
656 link.  If the file that the symbolic link points to is also within the
657 directory hierarchy you are searching with the @code{find} command,
658 you may not see a great deal of difference between these two
659 alternatives.
661 By default, @code{find} examines symbolic links themselves when it
662 finds them (and, if it later comes across the linked-to file, it will
663 examine that, too).  If you would prefer @code{find} to dereference
664 the links and examine the file that each link points to, specify the
665 @samp{-L} option to @code{find}.  You can explicitly specify the
666 default behaviour by using the @samp{-P} option.  The @samp{-H}
667 option is a half-way-between option which ensures that any symbolic
668 links listed on the command line are dereferenced, but other symbolic
669 links are not.
671 Symbolic links are different to ``hard links'' in the sense that you
672 need permission to search the directories
673 in the linked-to file name to
674 dereference the link.  This can mean that even if you specify the
675 @samp{-L} option, @code{find} may not be able to determine the
676 properties of the file that the link points to (because you don't have
677 sufficient permission).  In this situation, @code{find} uses the
678 properties of the link itself.  This also occurs if a symbolic link
679 exists but points to a file that is missing.
681 The options controlling the behaviour of @code{find} with respect to
682 links are as follows :-
684 @table @samp
685 @item -P
686 @code{find} does not dereference symbolic links at all.  This is the
687 default behaviour.  This option must be specified before any of the
688 file names on the command line.
689 @item -H
690 @code{find} does not dereference symbolic links (except in the case of
691 file names on the command line, which are dereferenced).  If a
692 symbolic link cannot be dereferenced, the information for the symbolic
693 link itself is used.  This option must be specified before any of the
694 file names on the command line.
695 @item -L
696 @code{find} dereferences symbolic links where possible, and where this
697 is not possible it uses the properties of the symbolic link itself.
698 This option must be specified before any of the file names on the
699 command line.  Use of this option also implies the same behaviour as
700 the @samp{-noleaf} option.  If you later use the @samp{-H} or
701 @samp{-P} options, this does not turn off @samp{-noleaf}.
703 @item -follow
704 This option forms part of the ``expression'' and must be specified
705 after the file names, but it is otherwise equivalent to @samp{-L}.
706 The @samp{-follow} option affects only those tests which appear after
707 it on the command line.  This option is deprecated.  Where possible,
708 you should use @samp{-L} instead.
709 @end table
711 The following differences in behavior occur when the @samp{-L} option
712 is used:
714 @itemize @bullet
715 @item
716 @code{find} follows symbolic links to directories when searching
717 directory trees.
718 @item
719 @samp{-lname} and @samp{-ilname} always return false (unless they
720 happen to match broken symbolic links).
721 @item
722 @samp{-type} reports the types of the files that symbolic links point
723 to.  This means that in combination with @samp{-L}, @samp{-type l}
724 will be true only for broken symbolic links.  To check for symbolic
725 links when @samp{-L} has been specified, use @samp{-xtype l}.
726 @item
727 Implies @samp{-noleaf} (@pxref{Directories}).
728 @end itemize
730 If the @samp{-L} option or the @samp{-H} option is used,
731 the file names used as arguments to @samp{-newer}, @samp{-anewer}, and
732 @samp{-cnewer} are dereferenced and the timestamp from the pointed-to
733 file is used instead (if possible -- otherwise the timestamp from the
734 symbolic link is used).
736 @deffn Test -lname pattern
737 @deffnx Test -ilname pattern
738 True if the file is a symbolic link whose contents match shell pattern
739 @var{pattern}.  For @samp{-ilname}, the match is case-insensitive.
740 @xref{Shell Pattern Matching}, for details about the @var{pattern}
741 argument.  If the @samp{-L} option is in effect, this test will always
742 return false for symbolic links unless they are broken.  So, to list
743 any symbolic links to @file{sysdep.c} in the current directory and its
744 subdirectories, you can do:
746 @example
747 find . -lname '*sysdep.c'
748 @end example
749 @end deffn
751 @node Hard Links
752 @subsection Hard Links
754 Hard links allow more than one name to refer to the same file.  To
755 find all the names which refer to the same file as NAME, use
756 @samp{-samefile NAME}.  If you are not using the @samp{-L} option, you
757 can confine your search to one filesystem using the @samp{-xdev}
758 option.  This is useful because hard links cannot point outside a
759 single filesystem, so this can cut down on needless searching.
761 If the @samp{-L} option is in effect, and NAME is in fact a symbolic
762 link, the symbolic link will be dereferenced.  Hence you are searching
763 for other links (hard or symbolic) to the file pointed to by NAME.  If
764 @samp{-L} is in effect but NAME is not itself a symbolic link, other
765 symbolic links to the file NAME will be matched.
767 You can also search for files by inode number.  This can occasionally
768 be useful in diagnosing problems with filesystems for example, because
769 @code{fsck} tends to print inode numbers.  Inode numbers also
770 occasionally turn up in log messages for some types of software, and
771 are used to support the @code{ftok()} library function.
773 You can learn a file's inode number and the number of links to it by
774 running @samp{ls -li} or @samp{find -ls}.
776 You can search for hard links to inode number NUM by using @samp{-inum
777 NUM}. If there are any filesystem mount points below the directory
778 where you are starting the search, use the @samp{-xdev} option unless
779 you are also using the @samp{-L} option.  Using @samp{-xdev} this
780 saves needless searching, since hard links to a file must be on the
781 same filesystem.  @xref{Filesystems}.
783 @deffn Test -samefile NAME
784 File is a hard link to the same inode as NAME.  If the @samp{-L}
785 option is in effect, symbolic links to the same file as NAME points to
786 are also matched.
787 @end deffn
789 @deffn Test -inum n
790 File has inode number @var{n}.  The @samp{+} and @samp{-} qualifiers
791 also work, though these are rarely useful.  Much of the time it is
792 easier to use @samp{-samefile} rather than this option.
793 @end deffn
795 You can also search for files that have a certain number of links,
796 with @samp{-links}.  Directories normally have at least two hard
797 links; their @file{.} entry is the second one.  If they have
798 subdirectories, each of those also has a hard link called @file{..} to
799 its parent directory.  The @file{.} and @file{..} directory entries
800 are not normally searched unless they are mentioned on the @code{find}
801 command line.
803 @deffn Test -links n
804 File has @var{n} hard links.
805 @end deffn
807 @deffn Test -links +n
808 File has more than @var{n} hard links.
809 @end deffn
811 @deffn Test -links -n
812 File has fewer than @var{n} hard links.
813 @end deffn
815 @node Time
816 @section Time
818 Each file has three time stamps, which record the last time that
819 certain operations were performed on the file:
821 @enumerate
822 @item
823 access (read the file's contents)
824 @item
825 change the status (modify the file or its attributes)
826 @item
827 modify (change the file's contents)
828 @end enumerate
830 Some systems also provide a timestamp that indicates when a file was
831 @emph{created}.   For example, the UFS2 fileystem under NetBSD-3.1
832 records the @emph{birth time} of each file.  This information is also
833 available under other versions of BSD and some versions of Cygwin.
834 However, even on systems which support file birth time, files may
835 exist for which this information was not recorded (for example, UFS1
836 file systems simply do not contain this information).
838 You can search for files whose time stamps are within a certain age
839 range, or compare them to other time stamps.
841 @menu
842 * Age Ranges::
843 * Comparing Timestamps::
844 @end menu
846 @node Age Ranges
847 @subsection Age Ranges
849 These tests are mainly useful with ranges (@samp{+@var{n}} and
850 @samp{-@var{n}}).
852 @deffn Test -atime n
853 @deffnx Test -ctime n
854 @deffnx Test -mtime n
855 True if the file was last accessed (or its status changed, or it was
856 modified) @var{n}*24 hours ago.  The number of 24-hour periods since
857 the file's timestamp is always rounded down; therefore 0 means ``less
858 than 24 hours ago'', 1 means ``between 24 and 48 hours ago'', and so
859 forth.  Fractional values are supported but this only really makes
860 sense for the case where ranges (@samp{+@var{n}} and @samp{-@var{n}})
861 are used.
862 @end deffn
864 @deffn Test -amin n
865 @deffnx Test -cmin n
866 @deffnx Test -mmin n
867 True if the file was last accessed (or its status changed, or it was
868 modified) @var{n} minutes ago.  These tests provide finer granularity
869 of measurement than @samp{-atime} et al., but rounding is done in a
870 similar way (again, fractions are supported).  For example, to list
871 files in @file{/u/bill} that were last read from 2 to 6 minutes ago:
873 @example
874 find /u/bill -amin +2 -amin -6
875 @end example
876 @end deffn
878 @deffn Option -daystart
879 Measure times from the beginning of today rather than from 24 hours
880 ago.  So, to list the regular files in your home directory that were
881 modified yesterday, do
883 @example
884 find ~/ -daystart -type f -mtime 1
885 @end example
887 The @samp{-daystart} option is unlike most other options in that it
888 has an effect on the way that other tests are performed.  The affected
889 tests are @samp{-amin}, @samp{-cmin}, @samp{-mmin}, @samp{-atime},
890 @samp{-ctime} and @samp{-mtime}.  The @samp{-daystart} option only
891 affects the behaviour of any tests which appear after it on the
892 command line.
893 @end deffn
895 @node Comparing Timestamps
896 @subsection Comparing Timestamps
898 @deffn Test -newerXY reference
899 Succeeds if timestamp @samp{X} of the file being considered is newer
900 than timestamp @samp{Y} of the file @file{reference}.   The latters
901 @samp{X} and @samp{Y} can be any of the following letters:
903 @table @samp
904 @item a
905 Last-access time of @file{reference}
906 @item B
907 Birth time of @file{reference} (when this is not known, the test cannot succeed)
908 @item c
909 Last-change time of @file{reference}
910 @item m
911 Last-modification time of @file{reference}
912 @item t
913 The @file{reference} argument is interpreted as a literal time, rather
914 than the name of a file.  @xref{Date input formats}, for a description
915 of how the timestamp is understood.  Tests of the form @samp{-newerXt}
916 are valid but tests of the form @samp{-newertY} are not.
917 @end table
919 For example the test @code{-newerac /tmp/foo} succeeds for all files
920 which have been accessed more recently than @file{/tmp/foo} was
921 changed.   Here @samp{X} is @samp{a} and @samp{Y} is @samp{c}.   
923 Not all files have a known birth time.  If @samp{Y} is @samp{b} and
924 the birth time of @file{reference} is not available, @code{find} exits
925 with an explanatory error message.  If @samp{X} is @samp{b} and we do
926 not know the birth time the file currently being considered, the test
927 simply fails (that is, it behaves like @code{-false} does).
929 Some operating systems (for example, most implementations of Unix) do
930 not support file birth times.  Some others, for example NetBSD-3.1,
931 do.  Even on operating systems which support file birth times, the
932 information may not be available for specific files.  For example,
933 under NetBSD, file birth times are supported on UFS2 file systems, but
934 not UFS1 file systems.
936 @end deffn
940 There are two ways to list files in @file{/usr} modified after
941 February 1 of the current year.  One uses @samp{-newermt}:
943 @example
944 find /usr -newermt "Feb 1"
945 @end example
947 The other way of doing this works on the versions of find before 4.3.3:
949 @c Idea from Rick Sladkey.
950 @example
951 touch -t 02010000 /tmp/stamp$$
952 find /usr -newer /tmp/stamp$$
953 rm -f /tmp/stamp$$
954 @end example
956 @deffn Test -anewer file
957 @deffnx Test -cnewer file
958 @deffnx Test -newer file
959 True if the file was last accessed (or its status changed, or it was
960 modified) more recently than @var{file} was modified.  These tests are
961 affected by @samp{-follow} only if @samp{-follow} comes before them on
962 the command line.  @xref{Symbolic Links}, for more information on
963 @samp{-follow}.  As an example, to list any files modified since
964 @file{/bin/sh} was last modified:
966 @example
967 find . -newer /bin/sh
968 @end example
969 @end deffn
971 @deffn Test -used n
972 True if the file was last accessed @var{n} days after its status was
973 last changed.  Useful for finding files that are not being used, and
974 could perhaps be archived or removed to save disk space.
975 @end deffn
977 @node Size
978 @section Size
980 @deffn Test -size n@r{[}bckwMG@r{]}
981 True if the file uses @var{n} units of space, rounding up.  The units
982 are 512-byte blocks by default, but they can be changed by adding a
983 one-character suffix to @var{n}:
985 @table @code
986 @item b
987 512-byte blocks (never 1024)
988 @item c
989 bytes
990 @item k
991 kilobytes (1024 bytes)
992 @item w
993 2-byte words
994 @item M
995 Megabytes (units of 1048576 bytes)
996 @item G
997 Gigabytes (units of 1073741824 bytes)
998 @end table
1000 The `b' suffix always considers blocks to be 512 bytes.  This is not
1001 affected by the setting (or non-setting) of the POSIXLY_CORRECT
1002 environment variable.  This behaviour is different to the behaviour of
1003 the @samp{-ls} action).  If you want to use 1024-byte units, use the
1004 `k' suffix instead.
1006 The number can be prefixed with a `+' or a `-'.  A plus sign indicates
1007 that the test should succeed if the file uses at least @var{n} units
1008 of storage (a common use of this test) and a minus sign
1009 indicates that the test should succeed if the file uses less than
1010 @var{n} units of storage.  There is no `=' prefix, because that's the
1011 default anyway.
1013 The size does not count indirect blocks, but it does count blocks in
1014 sparse files that are not actually allocated.  In other words, it's
1015 consistent with the result you get for @samp{ls -l} or @samp{wc -c}.
1016 This handling of sparse files differs from the output of the @samp{%k}
1017 and @samp{%b} format specifiers for the @samp{-printf} predicate.
1019 @end deffn
1021 @deffn Test -empty
1022 True if the file is empty and is either a regular file or a directory.
1023 This might help determine good candidates for deletion.  This test is
1024 useful with @samp{-depth} (@pxref{Directories}) and @samp{-delete}
1025 (@pxref{Single File}).
1026 @end deffn
1028 @node Type
1029 @section Type
1031 @deffn Test -type c
1032 True if the file is of type @var{c}:
1034 @table @code
1035 @item b
1036 block (buffered) special
1037 @item c
1038 character (unbuffered) special
1039 @item d
1040 directory
1041 @item p
1042 named pipe (FIFO)
1043 @item f
1044 regular file
1045 @item l
1046 symbolic link; if @samp{-L} is in effect, this is true only for broken
1047 symbolic links.  If you want to search for symbolic links when
1048 @samp{-L} is in effect, use @samp{-xtype} instead of @samp{-type}.
1049 @item s
1050 socket
1051 @item D
1052 door (Solaris)
1053 @end table
1054 @end deffn
1056 @deffn Test -xtype c
1057 This test behaves the same as @samp{-type} unless the file is a
1058 symbolic link.  If the file is a symbolic link, the result is as
1059 follows (in the table below, @samp{X} should be understood to
1060 represent any letter except @samp{l}):
1062 @table @samp
1063 @item @samp{-P -xtype l}
1064 True if the symbolic link is broken
1065 @item @samp{-P -xtype X}
1066 True if the (ultimate) target file is of type @samp{X}.
1067 @item @samp{-L -xtype l}
1068 Always true
1069 @item @samp{-L -xtype X}
1070 False unless the symbolic link is broken
1071 @end table
1073 In other words, for symbolic links, @samp{-xtype} checks the type of
1074 the file that @samp{-type} does not check.  
1076 The @samp{-H} option also affects the behaviour of @samp{-xtype}.
1077 When @samp{-H} is in effect, @samp{-xtype} behaves as if @samp{-L} had
1078 been specified when examining files listed on the command line, and as
1079 if @samp{-P} had been specified otherwise.  If neither @samp{-H} nor
1080 @samp{-L} was specified, @samp{-xtype} behaves as if @samp{-P} had
1081 been specified.
1083 @xref{Symbolic Links}, for more information on @samp{-follow} and
1084 @samp{-L}.
1085 @end deffn
1087 @node Owner
1088 @section Owner
1090 @deffn Test -user uname
1091 @deffnx Test -group gname
1092 True if the file is owned by user @var{uname} (belongs to group
1093 @var{gname}).  A numeric ID is allowed.
1094 @end deffn
1096 @deffn Test -uid n
1097 @deffnx Test -gid n
1098 True if the file's numeric user ID (group ID) is @var{n}.  These tests
1099 support ranges (@samp{+@var{n}} and @samp{-@var{n}}), unlike
1100 @samp{-user} and @samp{-group}.
1101 @end deffn
1103 @deffn Test -nouser
1104 @deffnx Test -nogroup
1105 True if no user corresponds to the file's numeric user ID (no group
1106 corresponds to the numeric group ID).  These cases usually mean that
1107 the files belonged to users who have since been removed from the
1108 system.  You probably should change the ownership of such files to an
1109 existing user or group, using the @code{chown} or @code{chgrp}
1110 program.
1111 @end deffn
1113 @node Mode Bits
1114 @section File Mode Bits
1116 @xref{File Permissions}, for information on how file mode bits are
1117 structured and how to specify them.
1119 Four tests determine what users can do with files.  These are
1120 @samp{-readable}, @samp{-writable}, @samp{-executable} and
1121 @samp{-perm}.  The first three tests ask the operating system if the
1122 current user can perform the relevant operation on a file, while
1123 @samp{-perm} just examines the file's mode.  The file mode may give
1124 a misleading impression of what the user can actually do, because the
1125 file may have an access control list, or exist on a read-only
1126 filesystem, for example.  Of these four tests though, only
1127 @samp{-perm} is specified by the POSIX standard.
1129 The @samp{-readable}, @samp{-writable} and @samp{-executable} tests
1130 are implemented via the @code{access} system call.  This is
1131 implemented within the operating system itself.  If the file being
1132 considered is on an NFS filesystem, the remote system may allow or
1133 forbid read or write operations for reasons of which the NFS client
1134 cannot take account.  This includes user-ID mapping, either in the
1135 general sense or the more restricted sense in which remote superusers
1136 are treated by the NFS server as if they are the local user
1137 @samp{nobody} on the NFS server.
1139 None of the tests in this section should be used to verify that a user
1140 is authorised to perform any operation (on the file being tested or
1141 any other file) because of the possibility of a race condition.  That
1142 is, the situation may change between the test and an action being
1143 taken on the basis of the result of that test.
1146 @deffn Test -readable 
1147 True if the file can be read by the invoking user.
1148 @end deffn
1150 @deffn Test -writable
1151 True if the file can be written by the invoking user.  This is an
1152 in-principle check, and other things may prevent a successful write
1153 operation; for example, the filesystem might be full.
1154 @end deffn
1156 @deffn Test -executable
1157 True if the file can be executed/searched by the invoking user.
1158 @end deffn
1160 @deffn Test -perm pmode
1162 True if the file's mode bits match @var{pmode}, which can be
1163 either a symbolic or numeric @var{mode} (@pxref{File Permissions})
1164 optionally prefixed by @samp{-} or @samp{/}.
1166 A @var{pmode} that starts with neither @samp{-} nor @samp{/} matches
1167 if @var{mode} exactly matches the file mode bits.
1169 A @var{pmode} that starts with @samp{-} matches if
1170 @emph{all} the file mode bits set in @var{mode} are set for the file;
1171 bits not set in @var{mode} are ignored.
1173 A @var{pmode} that starts with @samp{/} matches if
1174 @emph{any} of the file mode bits set in @var{mode} are set for the file;
1175 bits not set in @var{mode} are ignored.
1176 This is a GNU extension.
1178 If you don't use the @samp{/} or @samp{-} form with a symbolic mode
1179 string, you may have to specify a rather complex mode string.  For
1180 example @samp{-perm g=w} will only match files that have mode 0020
1181 (that is, ones for which group write permission is the only file mode bit
1182 set).  It is more likely that you will want to use the @samp{/} or
1183 @samp{-} forms, for example @samp{-perm -g=w}, which matches any file
1184 with group write permission.
1187 @table @samp
1188 @item -perm 664
1189 Match files that have read and write permission for their owner,
1190 and group, but that the rest of the world can read but not write to.
1191 Do not match files that meet these criteria but have other file mode
1192 bits set (for example if someone can execute/search the file).
1194 @item -perm -664
1195 Match files that have read and write permission for their owner,
1196 and group, but that the rest of the world can read but not write to,
1197 without regard to the presence of any extra file mode bits (for
1198 example the executable bit).  This matches a file with mode
1199 0777, for example.
1201 @item -perm /222
1202 Match files that are writable by somebody (their owner, or
1203 their group, or anybody else).
1205 @item -perm /022
1206 Match files that are writable by either their owner or their
1207 group.  The files don't have to be writable by both the owner and
1208 group to be matched; either will do.
1210 @item -perm /g+w,o+w
1211 As above.
1213 @item -perm /g=w,o=w
1214 As above.
1216 @item -perm -022
1217 Match files that are writable by both their owner and their
1218 group.
1220 @item -perm -444 -perm /222 ! -perm /111
1221 Match files that are readable for everybody, have at least one
1222 write bit set (i.e., somebody can write to them), but that cannot be
1223 executed/searched by anybody.  Note that in some shells the @samp{!} must be
1224 escaped;.
1226 @item -perm -a+r -perm /a+w ! -perm /a+x
1227 As above.
1230 @item -perm -g+w,o+w
1231 As above.
1232 @end table
1234 @quotation Warning
1235 If you specify @samp{-perm /000} or @samp{-perm /mode} where the
1236 symbolic mode @samp{mode} has no bits set, the test currently matches
1237 no files.  This differs from the behaviour of @samp{-perm -000}, which
1238 matches all files.  The behaviour of @samp{-perm /000} will be changed
1239 to be consistent with the behaviour of @samp{-perm -000}.  The change
1240 will probably be made in early 2006.
1241 @end quotation
1243 @end deffn
1245 @node Contents
1246 @section Contents
1248 To search for files based on their contents, you can use the
1249 @code{grep} program.  For example, to find out which C source files in
1250 the current directory contain the string @samp{thing}, you can do:
1252 @example
1253 grep -l thing *.[ch]
1254 @end example
1256 If you also want to search for the string in files in subdirectories,
1257 you can combine @code{grep} with @code{find} and @code{xargs}, like
1258 this:
1260 @example
1261 find . -name '*.[ch]' | xargs grep -l thing
1262 @end example
1264 The @samp{-l} option causes @code{grep} to print only the names of
1265 files that contain the string, rather than the lines that contain it.
1266 The string argument (@samp{thing}) is actually a regular expression,
1267 so it can contain metacharacters.  This method can be refined a little
1268 by using the @samp{-r} option to make @code{xargs} not run @code{grep}
1269 if @code{find} produces no output, and using the @code{find} action
1270 @samp{-print0} and the @code{xargs} option @samp{-0} to avoid
1271 misinterpreting files whose names contain spaces:
1273 @example
1274 find . -name '*.[ch]' -print0 | xargs -r -0 grep -l thing
1275 @end example
1277 For a fuller treatment of finding files whose contents match a
1278 pattern, see the manual page for @code{grep}.
1280 @node Directories
1281 @section Directories
1283 Here is how to control which directories @code{find} searches, and how
1284 it searches them.  These two options allow you to process a horizontal
1285 slice of a directory tree.
1287 @deffn Option -maxdepth levels
1288 Descend at most @var{levels} (a non-negative integer) levels of
1289 directories below the command line arguments.  @samp{-maxdepth 0}
1290 means only apply the tests and actions to the command line arguments.
1291 @end deffn
1293 @deffn Option -mindepth levels
1294 Do not apply any tests or actions at levels less than @var{levels} (a
1295 non-negative integer).  @samp{-mindepth 1} means process all files
1296 except the command line arguments.
1297 @end deffn
1299 @deffn Option -depth
1300 Process each directory's contents before the directory itself.  Doing
1301 this is a good idea when producing lists of files to archive with
1302 @code{cpio} or @code{tar}.  If a directory does not have write
1303 permission for its owner, its contents can still be restored from the
1304 archive since the directory's permissions are restored after its
1305 contents.
1306 @end deffn
1308 @deffn Option -d
1309 This is a deprecated synonym for @samp{-depth}, for compatibility with
1310 Mac OS X, FreeBSD and OpenBSD.  The @samp{-depth} option is a POSIX
1311 feature, so it is better to use that.
1312 @end deffn
1314 @deffn Action -prune
1315 If the file is a directory, do not descend into it.  The result is
1316 true.  For example, to skip the directory @file{src/emacs} and all
1317 files and directories under it, and print the names of the other files
1318 found:
1320 @example
1321 find . -wholename './src/emacs' -prune -o -print
1322 @end example
1324 The above command will not print @file{./src/emacs} among its list of
1325 results.  This however is not due to the effect of the @samp{-prune}
1326 action (which only prevents further descent, it doesn't make sure we
1327 ignore that item).  Instead, this effect is due to the use of
1328 @samp{-o}.  Since the left hand side of the ``or'' condition has
1329 succeeded for @file{./src/emacs}, it is not necessary to evaluate the
1330 right-hand-side (@samp{-print}) at all for this particular file.  If
1331 you wanted to print that directory name you could use either an extra
1332 @samp{-print} action:
1334 @example
1335 find . -wholename './src/emacs' -prune -print -o -print
1336 @end example
1338 or use the comma operator:
1340 @example
1341 find . -wholename './src/emacs' -prune , -print
1342 @end example
1344 If the @samp{-depth} option is in effect, the subdirectories will have
1345 already been visited in any case.  Hence @samp{-prune} has no effect
1346 and returns false.
1347 @end deffn
1350 @deffn Action -quit
1351 Exit immediately (with return value zero if no errors have occurred).
1352 This is different to @samp{-prune} because @samp{-prune} only applies
1353 to the contents of pruned directories, whilt @samp{-quit} simply makes
1354 @code{find} stop immediately.  No child processes will be left
1355 running, but no more files specified on the command line will be
1356 processed.  For example, @code{find /tmp/foo /tmp/bar -print -quit}
1357 will print only @samp{/tmp/foo}.  Any command lines which have been
1358 built by @samp{-exec ... \+} or @samp{-execdir ... \+} are invoked
1359 before the program is exited.
1360 @end deffn
1362 @deffn Option -noleaf
1363 Do not optimize by assuming that directories contain 2 fewer
1364 subdirectories than their hard link count.  This option is needed when
1365 searching filesystems that do not follow the Unix directory-link
1366 convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount
1367 points.  Each directory on a normal Unix filesystem has at least 2
1368 hard links: its name and its @file{.}  entry.  Additionally, its
1369 subdirectories (if any) each have a @file{..}  entry linked to that
1370 directory.  When @code{find} is examining a directory, after it has
1371 statted 2 fewer subdirectories than the directory's link count, it
1372 knows that the rest of the entries in the directory are
1373 non-directories (@dfn{leaf} files in the directory tree).  If only the
1374 files' names need to be examined, there is no need to stat them; this
1375 gives a significant increase in search speed.
1376 @end deffn
1378 @deffn Option -ignore_readdir_race
1379 If a file disappears after its name has been read from a directory but
1380 before @code{find} gets around to examining the file with @code{stat},
1381 don't issue an error message.  If you don't specify this option, an
1382 error message will be issued.  This option can be useful in system
1383 scripts (cron scripts, for example) that examine areas of the
1384 filesystem that change frequently (mail queues, temporary directories,
1385 and so forth), because this scenario is common for those sorts of
1386 directories.  Completely silencing error messages from @code{find} is
1387 undesirable, so this option neatly solves the problem.  There is no
1388 way to search one part of the filesystem with this option on and part
1389 of it with this option off, though.  When this option is turned on and 
1390 find discovers that one of the start-point files specified on the
1391 command line does not exist, no error message will be issued.
1393 @end deffn
1395 @deffn Option -noignore_readdir_race
1396 This option reverses the effect of the @samp{-ignore_readdir_race}
1397 option.
1398 @end deffn
1401 @node Filesystems
1402 @section Filesystems
1404 A @dfn{filesystem} is a section of a disk, either on the local host or
1405 mounted from a remote host over a network.  Searching network
1406 filesystems can be slow, so it is common to make @code{find} avoid
1407 them.
1409 There are two ways to avoid searching certain filesystems.  One way is
1410 to tell @code{find} to only search one filesystem:
1412 @deffn Option -xdev
1413 @deffnx Option -mount
1414 Don't descend directories on other filesystems.  These options are
1415 synonyms.
1416 @end deffn
1418 The other way is to check the type of filesystem each file is on, and
1419 not descend directories that are on undesirable filesystem types:
1421 @deffn Test -fstype type
1422 True if the file is on a filesystem of type @var{type}.  The valid
1423 filesystem types vary among different versions of Unix; an incomplete
1424 list of filesystem types that are accepted on some version of Unix or
1425 another is:
1426 @example
1427 ext2 ext3 proc sysfs ufs 4.2 4.3 nfs tmp mfs S51K S52K
1428 @end example
1429 You can use @samp{-printf} with the @samp{%F} directive to see the
1430 types of your filesystems.  The @samp{%D} directive shows the device
1431 number.  @xref{Print File Information}.  @samp{-fstype} is usually
1432 used with @samp{-prune} to avoid searching remote filesystems
1433 (@pxref{Directories}).
1434 @end deffn
1436 @node Combining Primaries With Operators
1437 @section Combining Primaries With Operators
1439 Operators build a complex expression from tests and actions.
1440 The operators are, in order of decreasing precedence:
1442 @table @code
1443 @item @asis{( @var{expr} )}
1444 @findex ()
1445 Force precedence.  True if @var{expr} is true.
1447 @item @asis{! @var{expr}}
1448 @itemx @asis{-not @var{expr}}
1449 @findex !
1450 @findex -not
1451 True if @var{expr} is false.  In some shells, it is necessary to
1452 protect the @samp{!} from shell interpretation by quoting it.
1454 @item @asis{@var{expr1 expr2}}
1455 @itemx @asis{@var{expr1} -a @var{expr2}}
1456 @itemx @asis{@var{expr1} -and @var{expr2}}
1457 @findex -a
1458 @findex -and
1459 And; @var{expr2} is not evaluated if @var{expr1} is false.
1461 @item @asis{@var{expr1} -o @var{expr2}}
1462 @itemx @asis{@var{expr1} -or @var{expr2}}
1463 @findex -o
1464 @findex -or
1465 Or; @var{expr2} is not evaluated if @var{expr1} is true.
1467 @item @asis{@var{expr1} , @var{expr2}}
1468 @findex ,
1469 List; both @var{expr1} and @var{expr2} are always evaluated.  True if
1470 @var{expr2} is true.  The value of @var{expr1} is discarded.  This
1471 operator lets you do multiple independent operations on one traversal,
1472 without depending on whether other operations succeeded.  The two
1473 operations @var{expr1} and @var{expr2} are not always fully
1474 independent, since @var{expr1} might have side effects like touching
1475 or deleting files, or it might use @samp{-prune} which would also
1476 affect @var{expr2}.
1477 @end table
1479 @code{find} searches the directory tree rooted at each file name by
1480 evaluating the expression from left to right, according to the rules
1481 of precedence, until the outcome is known (the left hand side is false
1482 for @samp{-and}, true for @samp{-or}), at which point @code{find}
1483 moves on to the next file name.
1485 There are two other tests that can be useful in complex expressions:
1487 @deffn Test -true
1488 Always true.
1489 @end deffn
1491 @deffn Test -false
1492 Always false.
1493 @end deffn
1495 @node Actions
1496 @chapter Actions
1498 There are several ways you can print information about the files that
1499 match the criteria you gave in the @code{find} expression.  You can
1500 print the information either to the standard output or to a file that
1501 you name.  You can also execute commands that have the file names as
1502 arguments.  You can use those commands as further filters to select
1503 files.
1505 @menu
1506 * Print File Name::
1507 * Print File Information::
1508 * Run Commands::
1509 * Delete Files::
1510 * Adding Tests::
1511 @end menu
1513 @node Print File Name
1514 @section Print File Name
1516 @deffn Action -print
1517 True; print the entire file name on the standard output, followed by a
1518 newline.  If there is the faintest possibility that one of the files
1519 for which you are searching might contain a newline, you should use
1520 @samp{-print0} instead.
1521 @end deffn
1523 @deffn Action -fprint file
1524 True; print the entire file name into file @var{file}, followed by a
1525 newline.  If @var{file} does not exist when @code{find} is run, it is
1526 created; if it does exist, it is truncated to 0 bytes.  The named
1527 output file is always created, even if no output is sent to it.  The
1528 file names @file{/dev/stdout} and @file{/dev/stderr} are handled
1529 specially; they refer to the standard output and standard error
1530 output, respectively.
1532 If there is the faintest possibility that one of the files for which
1533 you are searching might contain a newline, you should use
1534 @samp{-fprint0} instead.
1535 @end deffn
1538 @c @deffn Option -show-control-chars how
1539 @c This option affects how some of @code{find}'s actions treat
1540 @c unprintable characters in file names.  If @samp{how} is
1541 @c @samp{literal}, any subsequent actions (i.e., actions further on in the
1542 @c command line) print file names as-is.  
1543 @c 
1544 @c If this option is not specified, it currently defaults to @samp{safe}.
1545 @c If @samp{how} is @samp{safe}, C-like backslash escapes are used to
1546 @c indicate the non-printable characters for @samp{-ls} and @samp{-fls}.
1547 @c On the other hand, @samp{-print}, @samp{-fprint}, @samp{-fprintf} and
1548 @c @code{-printf} all quote unprintable characters if the data is going
1549 @c to a tty, and otherwise the data is emitted literally.
1550 @c 
1551 @c @table @code
1552 @c @item -ls
1553 @c Escaped if @samp{how} is @samp{safe}
1554 @c @item -fls
1555 @c Escaped if @samp{how} is @samp{safe}
1556 @c @item -print
1557 @c Always quoted if stdout is a tty,
1558 @c @samp{-show-control-chars} is ignored
1559 @c @item -print0
1560 @c Always literal, never escaped
1561 @c @item -fprint
1562 @c Always quoted if the destination is a tty;
1563 @c @samp{-show-control-chars} is ignored
1564 @c @item -fprint0
1565 @c Always literal, never escaped
1566 @c @item -fprintf
1567 @c If the destination is a tty, the @samp{%f}, 
1568 @c @samp{%F}, @samp{%h}, @samp{%l}, @samp{%p},
1569 @c and @samp{%P} directives produce quoted
1570 @c strings if stdout is a tty and are treated
1571 @c literally otherwise.
1572 @c @item -printf
1573 @c As for @code{-fprintf}.
1574 @c @end table
1575 @c @end deffn
1578 @node Print File Information
1579 @section Print File Information
1581 @deffn Action -ls
1582 True; list the current file in @samp{ls -dils} format on the standard
1583 output.  The output looks like this:
1585 @smallexample
1586 204744   17 -rw-r--r--   1 djm      staff       17337 Nov  2  1992 ./lwall-quotes
1587 @end smallexample
1589 The fields are:
1591 @enumerate
1592 @item
1593 The inode number of the file.  @xref{Hard Links}, for how to find
1594 files based on their inode number.
1596 @item
1597 the number of blocks in the file.  The block counts are of 1K blocks,
1598 unless the environment variable @code{POSIXLY_CORRECT} is set, in
1599 which case 512-byte blocks are used.  @xref{Size}, for how to find
1600 files based on their size.
1602 @item
1603 The file's type and file mode bits.  The type is shown as a dash for a
1604 regular file; for other file types, a letter like for @samp{-type} is
1605 used (@pxref{Type}).  The file mode bits are read, write, and execute/search for
1606 the file's owner, its group, and other users, respectively; a dash
1607 means the permission is not granted.  @xref{File Permissions}, for
1608 more details about file permissions.  @xref{Mode Bits}, for how to
1609 find files based on their file mode bits.
1611 @item
1612 The number of hard links to the file.
1614 @item
1615 The user who owns the file.
1617 @item
1618 The file's group.
1620 @item
1621 The file's size in bytes.
1623 @item
1624 The date the file was last modified.
1626 @item
1627 The file's name.  @samp{-ls} quotes non-printable characters in the
1628 file names using C-like backslash escapes.  This may change soon, as
1629 the treatment of unprintable characters is harmonised for @samp{-ls},
1630 @samp{-fls}, @samp{-print}, @samp{-fprint}, @samp{-printf} and
1631 @samp{-fprintf}.
1632 @end enumerate
1633 @end deffn
1635 @deffn Action -fls file
1636 True; like @samp{-ls} but write to @var{file} like @samp{-fprint}
1637 (@pxref{Print File Name}).  The named output file is always created,
1638 even if no output is sent to it.
1639 @end deffn
1641 @deffn Action -printf format
1642 True; print @var{format} on the standard output, interpreting @samp{\}
1643 escapes and @samp{%} directives.  Field widths and precisions can be
1644 specified as with the @code{printf} C function.  Format flags (like
1645 @samp{#} for example) may not work as you expect because many of the
1646 fields, even numeric ones, are printed with %s.  Numeric flags which
1647 are affected in this way include G, U, b, D, k and n.  This difference
1648 in behaviour means though that the format flag @samp{-} will work; it
1649 forces left-alignment of the field.  Unlike @samp{-print},
1650 @samp{-printf} does not add a newline at the end of the string.  If
1651 you want a newline at the end of the string, add a @samp{\n}.
1652 @end deffn
1654 @deffn Action -fprintf file format
1655 True; like @samp{-printf} but write to @var{file} like @samp{-fprint}
1656 (@pxref{Print File Name}).  The output file is always created, even if
1657 no output is ever sent to it.
1658 @end deffn
1660 @menu
1661 * Escapes::
1662 * Format Directives::
1663 * Time Formats::
1664 @end menu
1666 @node Escapes
1667 @subsection Escapes
1669 The escapes that @samp{-printf} and @samp{-fprintf} recognise are:
1671 @table @code
1672 @item \a
1673 Alarm bell.
1674 @item \b
1675 Backspace.
1676 @item \c
1677 Stop printing from this format immediately and flush the output.
1678 @item \f
1679 Form feed.
1680 @item \n
1681 Newline.
1682 @item \r
1683 Carriage return.
1684 @item \t
1685 Horizontal tab.
1686 @item \v
1687 Vertical tab.
1688 @item \\
1689 A literal backslash (@samp{\}).
1690 @item \0
1691 ASCII NUL.
1692 @item \NNN
1693 The character whose ASCII code is NNN (octal).
1694 @end table
1696 A @samp{\} character followed by any other character is treated as an
1697 ordinary character, so they both are printed, and a warning message is
1698 printed to the standard error output (because it was probably a typo).
1700 @node Format Directives
1701 @subsection Format Directives
1703 @samp{-printf} and @samp{-fprintf} support the following format
1704 directives to print information about the file being processed.  The C
1705 @code{printf} function, field width and precision specifiers are
1706 supported, as applied to string (%s) types. That is, you can specify
1707 "minimum field width"."maximum field width" for each directive.
1708 Format flags (like @samp{#} for example) may not work as you expect
1709 because many of the fields, even numeric ones, are printed with %s.
1710 The format flag @samp{-} does work; it forces left-alignment of the
1711 field.
1713 @samp{%%} is a literal percent sign.  A @samp{%} character followed by
1714 an unrecognised character (i.e., not a known directive or @code{printf}
1715 field width and precision specifier), is discarded (but the
1716 unrecognised character is printed), and a warning message is printed
1717 to the standard error output (because it was probably a typo).  Don't
1718 rely on this behaviour, because other directives may be added in the
1719 future.
1721 A @samp{%} at the end of the format argument causes undefined
1722 behaviour since there is no following character.  In some locales, it
1723 may hide your door keys, while in others it may remove the final page
1724 from the novel you are reading.
1726 @menu
1727 * Name Directives::
1728 * Ownership Directives::
1729 * Size Directives::
1730 * Location Directives::
1731 * Time Directives::
1732 * Formatting Flags::
1733 @end menu
1735 @node Name Directives
1736 @subsubsection Name Directives
1738 @table @code
1739 @item %p
1740 @c supports %-X.Yp
1741 File's name (not the absolute path name, but the name of the file as
1742 it was encountered by @code{find} - that is, as a relative path from
1743 one of the starting points).
1744 @item %f
1745 File's name with any leading directories removed (only the last
1746 element).
1747 @c supports %-X.Yf
1748 @item %h
1749 Leading directories of file's name (all but the last element and the
1750 slash before it).  If the file's name contains no slashes (for example
1751 because it was named on the command line and is in the current working
1752 directory), then ``%h'' expands to ``.''.  This prevents ``%h/%f''
1753 expanding to ``/foo'', which would be surprising and probably not
1754 desirable.
1755 @c supports %-X.Yh
1756 @item %P
1757 File's name with the name of the command line argument under which
1758 it was found removed from the beginning.
1759 @c supports %-X.YP
1760 @item %H
1761 Command line argument under which file was found.
1762 @c supports %-X.YH
1763 @end table
1765 @node Ownership Directives
1766 @subsubsection Ownership Directives
1768 @table @code
1769 @item %g
1770 @c supports %-X.Yg
1771 File's group name, or numeric group ID if the group has no name.
1772 @item %G
1773 @c supports %-X.Yg
1774 @c TODO: Needs to support # flag and 0 flag
1775 File's numeric group ID.
1776 @item %u
1777 @c supports %-X.Yu
1778 File's user name, or numeric user ID if the user has no name.
1779 @item %U
1780 @c supports %-X.Yu
1781 @c TODO: Needs to support # flag
1782 File's numeric user ID.
1783 @item %m
1784 @c full support, including # and 0.
1785 File's mode bits (in octal).  If you always want to have a leading
1786 zero on the number, use the '#' format flag, for example '%#m'.  
1788 The file mode bit numbers used are the traditional Unix
1789 numbers, which will be as expected on most systems, but if your
1790 system's file mode bit layout differs from the traditional Unix
1791 semantics, you will see a difference between the mode as printed by
1792 @samp{%m} and the mode as it appears in @code{struct stat}.
1794 @item %M
1795 File's type and mode bits (in symbolic form, as for @code{ls}).  This
1796 directive is supported in findutils 4.2.5 and later.
1797 @end table
1799 @node Size Directives
1800 @subsubsection Size Directives
1802 @table @code
1803 @item %k
1804 The amount of disk space used for this file in 1K blocks. Since disk
1805 space is allocated in multiples of the filesystem block size this is
1806 usually greater than %s/1024, but it can also be smaller if the file
1807 is a sparse file (that is, it has ``holes'').
1808 @item %b
1809 The amount of disk space used for this file in 512-byte blocks. Since
1810 disk space is allocated in multiples of the filesystem block size this
1811 is usually greater than %s/512, but it can also be smaller if the
1812 file is a sparse file (that is, it has ``holes'').
1813 @item %s
1814 File's size in bytes.
1815 @item %S
1816 File's sparseness.  This is calculated as @code{(BLOCKSIZE*st_blocks /
1817 st_size)}.  The exact value you will get for an ordinary file of a
1818 certain length is system-dependent.  However, normally sparse files
1819 will have values less than 1.0, and files which use indirect blocks
1820 and have few holes may have a value which is greater than 1.0.  The
1821 value used for BLOCKSIZE is system-dependent, but is usually 512
1822 bytes.  If the file size is zero, the value printed is undefined.  On
1823 systems which lack support for st_blocks, a file's sparseness is
1824 assumed to be 1.0.
1825 @end table
1827 @node Location Directives
1828 @subsubsection Location Directives
1830 @table @code
1831 @item %d
1832 File's depth in the directory tree (depth below a file named on the
1833 command line, not depth below the root directory).  Files named on the
1834 command line have a depth of 0.  Subdirectories immediately below them
1835 have a depth of 1, and so on.
1836 @item %D
1837 The device number on which the file exists (the @code{st_dev} field of
1838 @code{struct stat}), in decimal.
1839 @item %F
1840 Type of the filesystem the file is on; this value can be used for
1841 @samp{-fstype} (@pxref{Directories}).
1842 @item %l
1843 Object of symbolic link (empty string if file is not a symbolic link).
1844 @item %i
1845 File's inode number (in decimal).
1846 @item %n
1847 Number of hard links to file.
1848 @item %y
1849 Type of the file as used with @samp{-type}.  If the file is a symbolic
1850 link, @samp{l} will be printed.
1851 @item %Y
1852 Type of the file as used with @samp{-type}.  If the file is a symbolic
1853 link, it is dereferenced.  If the file is a broken symbolic link,
1854 @samp{N} is printed.
1856 @end table
1858 @node Time Directives
1859 @subsubsection Time Directives
1861 Some of these directives use the C @code{ctime} function.  Its output
1862 depends on the current locale, but it typically looks like
1864 @example
1865 Wed Nov  2 00:42:36 1994
1866 @end example
1868 @table @code
1869 @item %a
1870 File's last access time in the format returned by the C @code{ctime}
1871 function.
1872 @item %A@var{k}
1873 File's last access time in the format specified by @var{k}
1874 (@pxref{Time Formats}).
1875 @item %c
1876 File's last status change time in the format returned by the C
1877 @code{ctime} function.
1878 @item %C@var{k}
1879 File's last status change time in the format specified by @var{k}
1880 (@pxref{Time Formats}).
1881 @item %t
1882 File's last modification time in the format returned by the C
1883 @code{ctime} function.
1884 @item %T@var{k}
1885 File's last modification time in the format specified by @var{k}
1886 (@pxref{Time Formats}).
1887 @end table
1889 @node Time Formats
1890 @subsection Time Formats
1892 Below are the formats for the directives @samp{%A}, @samp{%C}, and
1893 @samp{%T}, which print the file's timestamps.  Some of these formats
1894 might not be available on all systems, due to differences in the C
1895 @code{strftime} function between systems.
1897 @menu
1898 * Time Components::
1899 * Date Components::
1900 * Combined Time Formats::
1901 @end menu
1903 @node Time Components
1904 @subsubsection Time Components
1906 The following format directives print single components of the time.
1908 @table @code
1909 @item H
1910 hour (00..23)
1911 @item I
1912 hour (01..12)
1913 @item k
1914 hour ( 0..23)
1915 @item l
1916 hour ( 1..12)
1917 @item p
1918 locale's AM or PM
1919 @item Z
1920 time zone (e.g., EDT), or nothing if no time zone is determinable
1921 @item M
1922 minute (00..59)
1923 @item S
1924 second (00..61).  There is a fractional part.
1925 @item @@
1926 seconds since Jan. 1, 1970, 00:00 GMT, with fractional part.
1927 @end table
1929 The fractional part of the seconds field is of indeterminate length
1930 and precision.  That is, the length of the fractional part of the
1931 seconds field will in general vary between findutils releases and
1932 between systems.  This means that it is unwise to assume that field
1933 has any specific length.  The length of this field is not usually a
1934 guide to the precision of timestamps in the underlying file system.
1938 @node Date Components
1939 @subsubsection Date Components
1941 The following format directives print single components of the date.
1943 @table @code
1944 @item a
1945 locale's abbreviated weekday name (Sun..Sat)
1946 @item A
1947 locale's full weekday name, variable length (Sunday..Saturday)
1948 @item b
1949 @itemx h
1950 locale's abbreviated month name (Jan..Dec)
1951 @item B
1952 locale's full month name, variable length (January..December)
1953 @item m
1954 month (01..12)
1955 @item d
1956 day of month (01..31)
1957 @item w
1958 day of week (0..6)
1959 @item j
1960 day of year (001..366)
1961 @item U
1962 week number of year with Sunday as first day of week (00..53)
1963 @item W
1964 week number of year with Monday as first day of week (00..53)
1965 @item Y
1966 year (1970@dots{})
1967 @item y
1968 last two digits of year (00..99)
1969 @end table
1971 @node Combined Time Formats
1972 @subsubsection Combined Time Formats
1974 The following format directives print combinations of time and date
1975 components.
1977 @table @code
1978 @item r
1979 time, 12-hour (hh:mm:ss [AP]M)
1980 @item T
1981 time, 24-hour (hh:mm:ss)
1982 @item X
1983 locale's time representation (H:M:S)
1984 @item c
1985 locale's date and time in ctime format (Sat Nov 04 12:02:33 EST
1986 1989).  This format does not include any fractional part in the
1987 seconds field.
1988 @item D
1989 date (mm/dd/yy)
1990 @item x
1991 locale's date representation (mm/dd/yy)
1992 @item +
1993 Date and time, separated by '+', for example
1994 `2004-04-28+22:22:05.0000000000'.
1995 The time is given in the current timezone (which may be affected by
1996 setting the TZ environment variable).  This is a GNU extension.  The
1997 seconds field includes a fractional part.
1998 @end table
2000 @node Formatting Flags
2001 @subsubsection Formatting Flags
2003 The @samp{%m} and @samp{%d} directives support the @samp{#}, @samp{0}
2004 and @samp{+} flags, but the other directives do not, even if they
2005 print numbers.  Numeric directives that do not support these flags
2006 include
2008 @samp{G},
2009 @samp{U},
2010 @samp{b},
2011 @samp{D},
2012 @samp{k} and
2013 @samp{n}.
2015 All fields support the format flag @samp{-}, which makes fields
2016 left-aligned.  That is, if the field width is greater than the actual
2017 contents of the field, the requisite number of spaces are printed
2018 after the field content instead of before it.
2020 @node Run Commands
2021 @section Run Commands
2023 You can use the list of file names created by @code{find} or
2024 @code{locate} as arguments to other commands.  In this way you can
2025 perform arbitrary actions on the files.
2027 @menu
2028 * Single File::
2029 * Multiple Files::
2030 * Querying::
2031 @end menu
2033 @node Single File
2034 @subsection Single File
2036 Here is how to run a command on one file at a time.
2038 @deffn Action -execdir command ;
2039 Execute @var{command}; true if zero status is returned.  @code{find}
2040 takes all arguments after @samp{-exec} to be part of the command until
2041 an argument consisting of @samp{;} is reached.  It replaces the string
2042 @samp{@{@}} by the current file name being processed everywhere it
2043 occurs in the command.  Both of these constructions need to be escaped
2044 (with a @samp{\}) or quoted to protect them from expansion by the
2045 shell.  The command is executed in the directory in which @code{find}
2046 was run.
2048 For example, to compare each C header file in or below the current
2049 directory with the file @file{/tmp/master}:
2051 @example
2052 find . -name '*.h' -execdir diff -u '@{@}' /tmp/master ';'
2053 @end example
2054 @end deffn
2056 If you use @samp{-execdir}, you must ensure that the current directory
2057 is not on @var{$PATH}, because otherwise an attacker could make
2058 @samp{find} run commands of their choice simply by leaving a
2059 suitably-named file in the right directory.  GNU find will refuse to
2060 run if you use @samp{-execdir} and the current directory is in
2061 @var{$PATH}.
2063 Another similar option, @samp{-exec} is supported, but is less secure.
2064 @xref{Security Considerations}, for a discussion of the security
2065 problems surrounding @samp{-exec}.
2068 @deffn Action -exec command ;
2069 This insecure variant of the @samp{-execdir} action is specified by
2070 POSIX.  The main difference is that the command is executed in the
2071 directory from which @code{find} was invoked, meaning that @samp{@{@}}
2072 is expanded to a relative path starting with the name of one of the
2073 starting directories, rather than just the basename of the matched
2074 file.
2076 While some implementations of @code{find} replace the @samp{@{@}} only
2077 where it appears on its own in an argument, GNU @code{find} replaces
2078 @samp{@{@}} wherever it appears.
2079 @end deffn
2082 @node Multiple Files
2083 @subsection Multiple Files
2085 Sometimes you need to process files one at a time.  But usually this
2086 is not necessary, and, it is faster to run a command on as many files
2087 as possible at a time, rather than once per file.  Doing this saves on
2088 the time it takes to start up the command each time.
2090 The @samp{-execdir} and @samp{-exec} actions have variants that build
2091 command lines containing as many matched files as possible.
2093 @deffn Action -execdir command @{@} +
2094 This works as for @samp{-execdir command ;}, except that the
2095 @samp{@{@}} at the end of the command is expanded to a list of names
2096 of matching files.  This expansion is done in such a way as to avoid
2097 exceeding the maximum command line length available on the system.
2098 Only one @samp{@{@}} is allowed within the command, and it must appear
2099 at the end, immediately before the @samp{+}.  A @samp{+} appearing in
2100 any position other than immediately after @samp{@{@}} is not
2101 considered to be special (that is, it does not terminate the command).
2102 @end deffn
2105 @deffn Action -exec command @{@} +
2106 This insecure variant of the @samp{-execdir} action is specified by
2107 POSIX.  The main difference is that the command is executed in the
2108 directory from which @code{find} was invoked, meaning that @samp{@{@}}
2109 is expanded to a relative path starting with the name of one of the
2110 starting directories, rather than just the basename of the matched
2111 file.
2112 @end deffn
2114 Before @code{find} exits, any partially-built command lines are
2115 executed.  This happens even if the exit was caused by the
2116 @samp{-quit} action.  However, some types of error (for example not
2117 being able to invoke @code{stat()} on the current directory) can cause
2118 an immediate fatal exit.  In this situation, any partially-built
2119 command lines will not be invoked (this prevents possible infinite
2120 loops).
2122 At first sight, it looks like the list of filenames to be processed
2123 can only be at the end of the command line, and that this might be a
2124 problem for some comamnds (@code{cp} and @code{rsync} for example).
2126 However, there is a slightly obscure but powerful workarouund for this
2127 problem which takes advantage of the behaviour of @code{sh -c}:-
2129 @example
2130 find startpoint -tests @dots{} -exec sh -c 'scp "$@@" remote:/dest' sh @{@} + 
2131 @end example
2133 In the example above, the filenames we want to work on need to occur
2134 on the @code{scp} command line before the name of the destination.  We
2135 use the shell to invoke the command @code{scp "$@@" remote:/dest} and
2136 the shell expands @code{"$@@"} to the list of filenames we want to
2137 process.
2139 Another, but less secure, way to run a command on more than one file
2140 at once, is to use the @code{xargs} command, which is invoked like
2141 this:
2143 @example
2144 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
2145 @end example
2147 @code{xargs} normally reads arguments from the standard input.  These
2148 arguments are delimited by blanks (which can be protected with double
2149 or single quotes or a backslash) or newlines.  It executes the
2150 @var{command} (default is @file{/bin/echo}) one or more times with any
2151 @var{initial-arguments} followed by arguments read from standard
2152 input.  Blank lines on the standard input are ignored.  If the
2153 @samp{-L} option is in use, trailing blanks indicate that @code{xargs}
2154 should consider the following line to be part of this one.
2156 Instead of blank-delimited names, it is safer to use @samp{find
2157 -print0} or @samp{find -fprint0} and process the output by giving the
2158 @samp{-0} or @samp{--null} option to GNU @code{xargs}, GNU @code{tar},
2159 GNU @code{cpio}, or @code{perl}.  The @code{locate} command also has a
2160 @samp{-0} or @samp{--null} option which does the same thing.
2162 You can use shell command substitution (backquotes) to process a list
2163 of arguments, like this:
2165 @example
2166 grep -l sprintf `find $HOME -name '*.c' -print`
2167 @end example
2169 However, that method produces an error if the length of the @samp{.c}
2170 file names exceeds the operating system's command line length limit.
2171 @code{xargs} avoids that problem by running the command as many times
2172 as necessary without exceeding the limit:
2174 @example
2175 find $HOME -name '*.c' -print | xargs grep -l sprintf
2176 @end example
2178 However, if the command needs to have its standard input be a terminal
2179 (@code{less}, for example), you have to use the shell command
2180 substitution method or use the @samp{--arg-file} option of
2181 @code{xargs}.
2183 The @code{xargs} command will process all its input, building command
2184 lines and executing them, unless one of the commands exits with a
2185 status of 255 (this will cause xargs to issue an error message and
2186 stop) or it reads a line contains the end of file string specified
2187 with the @samp{--eof} option.
2189 @menu
2190 * Unsafe File Name Handling::
2191 * Safe File Name Handling::
2192 * Unusual Characters in File Names::
2193 * Limiting Command Size::
2194 * Interspersing File Names::
2195 @end menu
2197 @node Unsafe File Name Handling
2198 @subsubsection Unsafe File Name Handling
2200 Because file names can contain quotes, backslashes, blank characters,
2201 and even newlines, it is not safe to process them using @code{xargs}
2202 in its default mode of operation.  But since most files' names do not
2203 contain blanks, this problem occurs only infrequently.  If you are
2204 only searching through files that you know have safe names, then you
2205 need not be concerned about it.
2207 Error messages issued by @code{find} and @code{locate} quote unusual
2208 characters in file names in order to prevent unwanted changes in the
2209 terminal's state.
2212 @c This example is adapted from:
2213 @c From: pfalstad@stone.Princeton.EDU (Paul John Falstad)
2214 @c Newsgroups: comp.unix.shell
2215 @c Subject: Re: Beware xargs security holes
2216 @c Date: 16 Oct 90 19:12:06 GMT
2218 In many applications, if @code{xargs} botches processing a file
2219 because its name contains special characters, some data might be lost.
2220 The importance of this problem depends on the importance of the data
2221 and whether anyone notices the loss soon enough to correct it.
2222 However, here is an extreme example of the problems that using
2223 blank-delimited names can cause.  If the following command is run
2224 daily from @code{cron}, then any user can remove any file on the
2225 system:
2227 @example
2228 find / -name '#*' -atime +7 -print | xargs rm
2229 @end example
2231 For example, you could do something like this:
2233 @example
2234 eg$ echo > '#
2235 vmunix'
2236 @end example
2238 @noindent
2239 and then @code{cron} would delete @file{/vmunix}, if it ran
2240 @code{xargs} with @file{/} as its current directory.
2242 To delete other files, for example @file{/u/joeuser/.plan}, you could
2243 do this:
2245 @example
2246 eg$ mkdir '#
2248 eg$ cd '#
2250 eg$ mkdir u u/joeuser u/joeuser/.plan'
2252 eg$ echo > u/joeuser/.plan'
2253 /#foo'
2254 eg$ cd ..
2255 eg$ find . -name '#*' -print | xargs echo
2256 ./# ./# /u/joeuser/.plan /#foo
2257 @end example
2259 @node Safe File Name Handling
2260 @subsubsection Safe File Name Handling
2262 Here is how to make @code{find} output file names so that they can be
2263 used by other programs without being mangled or misinterpreted.  You
2264 can process file names generated this way by giving the @samp{-0} or
2265 @samp{--null} option to GNU @code{xargs}, GNU @code{tar}, GNU
2266 @code{cpio}, or @code{perl}.
2268 @deffn Action -print0
2269 True; print the entire file name on the standard output, followed by a
2270 null character.
2271 @end deffn
2273 @deffn Action -fprint0 file
2274 True; like @samp{-print0} but write to @var{file} like @samp{-fprint}
2275 (@pxref{Print File Name}).  The output file is always created.
2276 @end deffn
2278 As of findutils version 4.2.4, the @code{locate} program also has a
2279 @samp{--null} option which does the same thing.  For similarity with
2280 @code{xargs}, the short form of the option @samp{-0} can also be used.
2282 If you want to be able to handle file names safely but need to run
2283 commands which want to be connected to a terminal on their input, you
2284 can use the @samp{--arg-file} option to @code{xargs} like this:
2286 @example
2287 find / -name xyzzy -print0 > list
2288 xargs --null --arg-file=list munge
2289 @end example
2291 The example above runs the @code{munge} program on all the files named
2292 @file{xyzzy} that we can find, but @code{munge}'s input will still be
2293 the terminal (or whatever the shell was using as standard input).  If
2294 your shell has the ``process substitution'' feature @samp{<(...)}, you
2295 can do this in just one step:
2297 @example
2298 xargs --null --arg-file=<(find / -name xyzzy -print0) munge
2299 @end example
2301 @node Unusual Characters in File Names
2302 @subsubsection Unusual Characters in File Names
2303 As discussed above, you often need to be careful about how the names
2304 of files are handled by @code{find} and other programs.  If the output
2305 of @code{find} is not going to another program but instead is being
2306 shown on a terminal, this can still be a problem.  For example, some
2307 character sequences can reprogram the function keys on some terminals.
2308 @xref{Security Considerations}, for a discussion of other security
2309 problems relating to @code{find}.
2311 Unusual characters are handled differently by various
2312 actions, as described below.
2314 @table @samp
2315 @item -print0
2316 @itemx -fprint0
2317 Always print the exact file name, unchanged, even if the output is
2318 going to a terminal.
2319 @item -ok
2320 @itemx -okdir
2321 Always print the exact file name, unchanged.  This will probably
2322 change in a future release.
2323 @item -ls
2324 @itemx -fls
2325 Unusual characters are always escaped.  White space, backslash, and
2326 double quote characters are printed using C-style escaping (for
2327 example @samp{\f}, @samp{\"}).  Other unusual characters are printed
2328 using an octal escape.  Other printable characters (for @samp{-ls} and
2329 @samp{-fls} these are the characters between octal 041 and 0176) are
2330 printed as-is.
2331 @item -printf
2332 @itemx -fprintf
2333 If the output is not going to a terminal, it is printed as-is.
2334 Otherwise, the result depends on which directive is in use:
2336 @table @asis
2337 @item %D, %F, %H, %Y, %y
2338 These expand to values which are not under control of files' owners,
2339 and so are printed as-is.
2340 @item  %a, %b, %c, %d, %g, %G, %i, %k, %m, %M, %n, %s, %t, %u, %U
2341 These have values which are under the control of files' owners but
2342 which cannot be used to send arbitrary data to the terminal, and so
2343 these are printed as-is.
2344 @item %f, %h, %l, %p, %P
2345 The output of these directives is quoted if the output is going to a
2346 terminal.
2348 This quoting is performed in the same way as for GNU @code{ls}.  This
2349 is not the same quoting mechanism as the one used for @samp{-ls} and
2350 @samp{fls}.  If you are able to decide what format to use for the
2351 output of @code{find} then it is normally better to use @samp{\0} as a
2352 terminator than to use newline, as file names can contain white space
2353 and newline characters.
2354 @end table
2355 @item -print
2356 @itemx -fprint
2357 Quoting is handled in the same way as for the @samp{%p} directive of
2358 @samp{-printf} and @samp{-fprintf}.  If you are using @code{find} in a
2359 script or in a situation where the matched files might have arbitrary
2360 names, you should consider using @samp{-print0} instead of
2361 @samp{-print}.
2362 @end table
2365 The @code{locate} program quotes and escapes unusual characters in
2366 file names in the same way as @code{find}'s @samp{-print} action.
2368 The behaviours described above may change soon, as the treatment of
2369 unprintable characters is harmonised for @samp{-ls}, @samp{-fls},
2370 @samp{-print}, @samp{-fprint}, @samp{-printf} and @samp{-fprintf}.
2372 @node Limiting Command Size
2373 @subsubsection Limiting Command Size
2375 @code{xargs} gives you control over how many arguments it passes to
2376 the command each time it executes it.  By default, it uses up to
2377 @code{ARG_MAX} - 2k, or 128k, whichever is smaller, characters per
2378 command.  It uses as many lines and arguments as fit within that
2379 limit.  The following options modify those values.
2381 @table @code
2382 @item --no-run-if-empty
2383 @itemx -r
2384 If the standard input does not contain any nonblanks, do not run the
2385 command.  By default, the command is run once even if there is no
2386 input.  This option is a GNU extension.
2388 @item --max-lines@r{[}=@var{max-lines}@r{]}
2389 @itemx -L @var{max-lines}
2390 @itemx -l@r{[}@var{max-lines}@r{]}
2391 Use at most @var{max-lines} nonblank input lines per command line;
2392 @var{max-lines} defaults to 1 if omitted; omitting the argument is not
2393 allowed in the case of the @samp{-L} option.  Trailing blanks cause an
2394 input line to be logically continued on the next input line, for the
2395 purpose of counting the lines.  Implies @samp{-x}.  The preferred name
2396 for this option is @samp{-L} as this is specified by POSIX.  
2398 @item --max-args=@var{max-args}
2399 @itemx -n @var{max-args}
2400 Use at most @var{max-args} arguments per command line.  Fewer than
2401 @var{max-args} arguments will be used if the size (see the @samp{-s}
2402 option) is exceeded, unless the @samp{-x} option is given, in which
2403 case @code{xargs} will exit.
2405 @item --max-chars=@var{max-chars}
2406 @itemx -s @var{max-chars}
2407 Use at most @var{max-chars} characters per command line, including the
2408 command initial arguments and the terminating nulls at the ends of the
2409 argument strings.  If you specify a value for this option which is too
2410 large or small, a warning message is printed and the appropriate upper
2411 or lower limit is used instead.  You can use @samp{--show-limits}
2412 option to understand the command-line limits applying to @code{xargs}
2413 and how this is affected by any other options.  The POSIX limits shown
2414 when you do this have already been adjusted to take into account the
2415 size of your environment variables.  
2417 The largest allowed value is system-dependent, and is calculated as
2418 the argument length limit for exec, less the size of your environment,
2419 less 2048 bytes of headroom.  If this value is more than 128KiB,
2420 128Kib is used as the default value; otherwise, the default value is
2421 the maximum.
2424 @item --max-procs=@var{max-procs}
2425 @itemx -P @var{max-procs}
2426 Run up to @var{max-procs} processes at a time; the default is 1.  If
2427 @var{max-procs} is 0, @code{xargs} will run as many processes as
2428 possible at a time.  Use the @samp{-n}, @samp{-s}, or @samp{-L} option
2429 with @samp{-P}; otherwise chances are that the command will be run
2430 only once.
2431 @end table
2433 @node Interspersing File Names
2434 @subsubsection Interspersing File Names
2436 @code{xargs} can insert the name of the file it is processing between
2437 arguments you give for the command.  Unless you also give options to
2438 limit the command size (@pxref{Limiting Command Size}), this mode of
2439 operation is equivalent to @samp{find -exec} (@pxref{Single File}).
2441 @table @code
2442 @item --replace@r{[}=@var{replace-str}@r{]}
2443 @itemx -I @var{replace-str}
2444 @itemx -i @var{replace-str}
2445 Replace occurrences of @var{replace-str} in the initial arguments with
2446 names read from the input.  Also, unquoted blanks do not terminate
2447 arguments; instead, the input is split at newlines only.  For the
2448 @samp{-i} option, if @var{replace-str} is omitted for @samp{--replace}
2449 or @samp{-i}, it defaults to @samp{@{@}} (like for @samp{find -exec}).
2450 Implies @samp{-x} and @samp{-l 1}.  @samp{-i} is deprecated in favour
2451 of @samp{-I}. As an example, to sort each file in the @file{bills}
2452 directory, leaving the output in that file name with @file{.sorted}
2453 appended, you could do:
2455 @example
2456 find bills -type f | xargs -I XX sort -o XX.sorted XX
2457 @end example
2459 @noindent
2460 The equivalent command using @samp{find -execdir} is:
2462 @example
2463 find bills -type f -execdir sort -o '@{@}.sorted' '@{@}' ';'
2464 @end example
2465 @end table
2468 When you use the @samp{-I} option, each line read from the input is
2469 buffered internally.  This means that there is an upper limit on the
2470 length of input line that xargs will accept when used with the
2471 @samp{-I} option.  To work around this limitation, you can use the
2472 @samp{-s} option to increase the amount of buffer space that xargs
2473 uses, and you can also use an extra invocation of xargs to ensure that
2474 very long lines do not occur.  For example:
2476 @example
2477 somecommand | xargs -s 50000 echo | xargs -I '@{@}' -s 100000 rm '@{@}'
2478 @end example
2480 Here, the first invocation of @code{xargs} has no input line length
2481 limit because it doesn't use the @samp{-I} option. The second
2482 invocation of @code{xargs} does have such a limit, but we have ensured
2483 that the it never encounters a line which is longer than it can
2484 handle.  
2486 This is not an ideal solution.  Instead, the @samp{-I} option should
2487 not impose a line length limit (apart from any limit imposed by the
2488 operating system) and so one might consider this limitation to be a
2489 bug.  A better solution would be to allow @code{xargs -I} to
2490 automatically move to a larger value for the @samp{-s} option when
2491 this is needed.
2493 This sort of problem doesn't occur with the output of @code{find}
2494 because it emits just one filename per line.
2496 @node Querying
2497 @subsection Querying
2499 To ask the user whether to execute a command on a single file, you can
2500 use the @code{find} primary @samp{-okdir} instead of @samp{-execdir},
2501 and the @code{find} primary @samp{-ok} instead of @samp{-exec}:
2503 @deffn Action -okdir command ;
2504 Like @samp{-execdir} (@pxref{Single File}), but ask the user first (on
2505 the standard input); if the response does not start with @samp{y} or
2506 @samp{Y}, do not run the command, and return false.  If the command is
2507 run, its standard input is redirected from @file{/dev/null}.
2508 @end deffn
2510 @deffn Action -ok command ;
2511 This insecure variant of the @samp{-okdir} action is specified by
2512 POSIX.  The main difference is that the command is executed in the
2513 directory from which @code{find} was invoked, meaning that @samp{@{@}}
2514 is expanded to a relative path starting with the name of one of the
2515 starting directories, rather than just the basename of the matched
2516 file.  If the command is run, its standard input is redirected from
2517 @file{/dev/null}.
2518 @end deffn
2520 When processing multiple files with a single command, to query the
2521 user you give @code{xargs} the following option.  When using this
2522 option, you might find it useful to control the number of files
2523 processed per invocation of the command (@pxref{Limiting Command
2524 Size}).
2526 @table @code
2527 @item --interactive
2528 @itemx -p
2529 Prompt the user about whether to run each command line and read a line
2530 from the terminal.  Only run the command line if the response starts
2531 with @samp{y} or @samp{Y}.  Implies @samp{-t}.
2532 @end table
2534 @node Delete Files
2535 @section Delete Files
2537 @deffn Action -delete
2538 Delete files or directories; true if removal succeeded.  If the
2539 removal failed, an error message is issued.
2541 The use of the @samp{-delete} action on the command line automatically
2542 turns on the @samp{-depth} option (@pxref{find Expressions}).
2543 @end deffn
2545 @node Adding Tests
2546 @section Adding Tests
2548 You can test for file attributes that none of the @code{find} builtin
2549 tests check.  To do this, use @code{xargs} to run a program that
2550 filters a list of files printed by @code{find}.  If possible, use
2551 @code{find} builtin tests to pare down the list, so the program run by
2552 @code{xargs} has less work to do.  The tests builtin to @code{find}
2553 will likely run faster than tests that other programs perform.
2555 For reasons of efficiency it is often useful to limit the number of
2556 times an external program has to be run.  For this reason, it is often
2557 a good idea to implement ``extended'' tests by using @code{xargs}.
2559 For example, here is a way to print the names of all of the unstripped
2560 binaries in the @file{/usr/local} directory tree.  Builtin tests avoid
2561 running @code{file} on files that are not regular files or are not
2562 executable.
2564 @example
2565 find /usr/local -type f -perm /a=x | xargs file |
2566   grep 'not stripped' | cut -d: -f1
2567 @end example
2569 @noindent
2570 The @code{cut} program removes everything after the file name from the
2571 output of @code{file}.
2573 However, using @code{xargs} can present important security problems
2574 (@pxref{Security Considerations}).  These can be avoided by using
2575 @samp{-execdir}.  The @samp{-execdir} action is also a useful way of
2576 putting your own test in the middle of a set of other tests or actions
2577 for @code{find} (for example, you might want to use @samp{-prune}).
2579 @c Idea from Martin Weitzel.
2580 To place a special test somewhere in the middle of a @code{find}
2581 expression, you can use @samp{-execdir} (or, less securely,
2582 @samp{-exec}) to run a program that performs the test.  Because
2583 @samp{-execdir} evaluates to the exit status of the executed program,
2584 you can use a program (which can be a shell script) that tests for a
2585 special attribute and make it exit with a true (zero) or false
2586 (non-zero) status.  It is a good idea to place such a special test
2587 @emph{after} the builtin tests, because it starts a new process which
2588 could be avoided if a builtin test evaluates to false.
2590 Here is a shell script called @code{unstripped} that checks whether
2591 its argument is an unstripped binary file:
2593 @example
2594 #! /bin/sh
2595 file "$1" | grep -q "not stripped"
2596 @end example
2599 This script relies on the shell exiting with the status of
2600 the last command in the pipeline, in this case @code{grep}.  The
2601 @code{grep} command exits with a true status if it found any matches,
2602 false if not.  Here is an example of using the script (assuming it is
2603 in your search path).  It lists the stripped executables (and shell
2604 scripts) in the file @file{sbins} and the unstripped ones in
2605 @file{ubins}.
2607 @example
2608 find /usr/local -type f -perm /a=x \
2609   \( -execdir unstripped '@{@}' \; -fprint ubins -o -fprint sbins \)
2610 @end example
2613 @node Databases
2614 @chapter File Name Databases
2616 The file name databases used by @code{locate} contain lists of files
2617 that were in particular directory trees when the databases were last
2618 updated.  The file name of the default database is determined when
2619 @code{locate} and @code{updatedb} are configured and installed.  The
2620 frequency with which the databases are updated and the directories for
2621 which they contain entries depend on how often @code{updatedb} is run,
2622 and with which arguments.
2624 You can obtain some statistics about the databases by using
2625 @samp{locate --statistics}.
2627 @menu
2628 * Database Locations::
2629 * Database Formats::
2630 * Newline Handling::
2631 @end menu
2634 @node Database Locations
2635 @section Database Locations
2637 There can be multiple file name databases.  Users can select which
2638 databases @code{locate} searches using the @code{LOCATE_PATH}
2639 environment variable or a command line option.  The system
2640 administrator can choose the file name of the default database, the
2641 frequency with which the databases are updated, and the directories
2642 for which they contain entries.  File name databases are updated by
2643 running the @code{updatedb} program, typically nightly.
2645 In networked environments, it often makes sense to build a database at
2646 the root of each filesystem, containing the entries for that
2647 filesystem.  @code{updatedb} is then run for each filesystem on the
2648 fileserver where that filesystem is on a local disk, to prevent
2649 thrashing the network.
2651 @xref{Invoking updatedb}, for the description of the options to
2652 @code{updatedb}.  These options can be used to specify which
2653 directories are indexed by each database file.
2655 The default location for the locate database depends on how findutils
2656 is built, but the findutils installation accompanying this manual uses
2657 the default location @file{@value{LOCATE_DB}}.
2659 If no database exists at @file{@value{LOCATE_DB}} but the user did not
2660 specify where to look (by using @samp{-d} or setting
2661 @code{LOCATE_PATH}), then @code{locate} will also check for a
2662 ``secure'' database in @file{/var/lib/slocate/slocate.db}.
2664 @node Database Formats
2665 @section Database Formats
2667 The file name databases contain lists of files that were in particular
2668 directory trees when the databases were last updated.  The file name
2669 database format changed starting with GNU @code{locate} version 4.0 to
2670 allow machines with different byte orderings to share the databases.
2672 GNU @code{locate} can read both the old and new database formats.
2673 However, old versions of @code{locate} (on other Unix systems, or GNU
2674 @code{locate} before version 4.0) produce incorrect results if run
2675 against a database in something other than the old format.
2677 Support for the old database format will eventually be discontinued,
2678 first in @code{updatedb} and later in @code{locate}.
2680 If you run @samp{locate --statistics}, the resulting summary indicates
2681 the type of each @code{locate} database.   You select which database
2682 format @code{updatedb} will use with the @samp{--dbformat} option.
2685 @menu
2686 * LOCATE02 Database Format::
2687 * Sample LOCATE02 Database::
2688 * slocate Database Format::
2689 * Old Database Format::
2690 @end menu
2692 @node LOCATE02 Database Format
2693 @subsection LOCATE02 Database Format
2695 @code{updatedb} runs a program called @code{frcode} to
2696 @dfn{front-compress} the list of file names, which reduces the
2697 database size by a factor of 4 to 5.  Front-compression (also known as
2698 incremental encoding) works as follows.
2700 The database entries are a sorted list (case-insensitively, for users'
2701 convenience).  Since the list is sorted, each entry is likely to share
2702 a prefix (initial string) with the previous entry.  Each database
2703 entry begins with an offset-differential count byte, which is the
2704 additional number of characters of prefix of the preceding entry to
2705 use beyond the number that the preceding entry is using of its
2706 predecessor.  (The counts can be negative.)  Following the count is a
2707 null-terminated ASCII remainder---the part of the name that follows
2708 the shared prefix.
2710 If the offset-differential count is larger than can be stored in a
2711 byte (+/-127), the byte has the value 0x80 and the count follows in a
2712 2-byte word, with the high byte first (network byte order).
2714 Every database begins with a dummy entry for a file called
2715 @file{LOCATE02}, which @code{locate} checks for to ensure that the
2716 database file has the correct format; it ignores the entry in doing
2717 the search.
2719 Databases cannot be concatenated together, even if the first (dummy)
2720 entry is trimmed from all but the first database.  This is because the
2721 offset-differential count in the first entry of the second and
2722 following databases will be wrong.
2724 In the output of @samp{locate --statistics}, the new database format
2725 is referred to as @samp{LOCATE02}.
2727 @node Sample LOCATE02 Database
2728 @subsection Sample LOCATE02 Database
2730 Sample input to @code{frcode}:
2731 @c with nulls changed to newlines:
2733 @example
2734 /usr/src
2735 /usr/src/cmd/aardvark.c
2736 /usr/src/cmd/armadillo.c
2737 /usr/tmp/zoo
2738 @end example
2740 Length of the longest prefix of the preceding entry to share:
2742 @example
2743 0 /usr/src
2744 8 /cmd/aardvark.c
2745 14 rmadillo.c
2746 5 tmp/zoo
2747 @end example
2749 Output from @code{frcode}, with trailing nulls changed to newlines
2750 and count bytes made printable:
2752 @example
2753 0 LOCATE02
2754 0 /usr/src
2755 8 /cmd/aardvark.c
2756 6 rmadillo.c
2757 -9 tmp/zoo
2758 @end example
2760 (6 = 14 - 8, and -9 = 5 - 14)
2762 @node slocate Database Format
2763 @subsection slocate Database Format
2765 The @code{slocate} program uses a database format similar to, but not
2766 quite the same as, GNU @code{locate}.  The first byte of the database
2767 specifies its @dfn{security level}.  If the security level is 0,
2768 @code{slocate} will read, match and print filenames on the basis of
2769 the information in the database only.  However, if the security level
2770 byte is 1, @code{slocate} omits entries from its output if the
2771 invoking user is unable to access them.  The second byte of the
2772 database is zero.  The second byte is immediately followed by the
2773 first database entry.  The first entry in the database is not preceded
2774 by any differential count or dummy entry.  Instead the differential
2775 count for the first item is assumed to be zero.
2777 Starting with the second entry (if any) in the database, data is
2778 interpreted as for the GNU LOCATE02 format.
2780 @node Old Database Format
2781 @subsection Old Database Format
2783 The old database format is used by Unix @code{locate} and @code{find}
2784 programs and earlier releases of the GNU ones.  @code{updatedb}
2785 produces this format if given the @samp{--old-format} option.
2787 @code{updatedb} runs programs called @code{bigram} and @code{code} to
2788 produce old-format databases.  The old format differs from the new one
2789 in the following ways.  Instead of each entry starting with an
2790 offset-differential count byte and ending with a null, byte values
2791 from 0 through 28 indicate offset-differential counts from -14 through
2792 14.  The byte value indicating that a long offset-differential count
2793 follows is 0x1e (30), not 0x80.  The long counts are stored in host
2794 byte order, which is not necessarily network byte order, and host
2795 integer word size, which is usually 4 bytes.  They also represent a
2796 count 14 less than their value.  The database lines have no
2797 termination byte; the start of the next line is indicated by its first
2798 byte having a value <= 30.
2800 In addition, instead of starting with a dummy entry, the old database
2801 format starts with a 256 byte table containing the 128 most common
2802 bigrams in the file list.  A bigram is a pair of adjacent bytes.
2803 Bytes in the database that have the high bit set are indexes (with the
2804 high bit cleared) into the bigram table.  The bigram and
2805 offset-differential count coding makes these databases 20-25% smaller
2806 than the new format, but makes them not 8-bit clean.  Any byte in a
2807 file name that is in the ranges used for the special codes is replaced
2808 in the database by a question mark, which not coincidentally is the
2809 shell wildcard to match a single character.
2811 The old format therefore cannot faithfully store entries with
2812 non-ASCII characters. It therefore should not be used in
2813 internationalised environments.  That is, most installations should
2814 not use it.
2816 Because the long counts are stored by the @code{code} program as
2817 native-order machine words, the database format is not eaily used in
2818 environments which differ in terms of byte order.  If locate databases
2819 are to be shared between machines, the LOCATE02 database format should
2820 be used.  This has other benefits as discussed above.  However, the
2821 length of the filename currently being processed can normally be used
2822 to place reasonable limits on the long counts and so this information
2823 is used by locate to help it guess the byte ordering of the old format
2824 database.  Unless it finds evidence to the contrary, @code{locate}
2825 will assume that the byte order of the database is the same as the
2826 native byte order of the machine running @code{locate}.  The output of
2827 @samp{locate --statistics} also includes information about the byte
2828 order of old-format databases.
2830 The output of @samp{locate --statistics} will give an incorrect count
2831 of the number of file names containing newlines or high-bit characters
2832 for old-format databases.
2834 Old versions of GNU @code{locate} fail to correctly handle very long
2835 file names, possibly leading to security problems relating to a heap
2836 buffer overrun.  @xref{Security Considerations for locate}, for a
2837 detailed explanation.
2839 @node Newline Handling
2840 @section Newline Handling
2842 Within the database, file names are terminated with a null character.
2843 This is the case for both the old and the new format.
2845 When the new database format is being used, the compression technique
2846 used to generate the database though relies on the ability to sort the
2847 list of files before they are presented to @code{frcode}.
2849 If the system's sort command allows its input list of files to be
2850 separated with null characters via the @samp{-z} option, this option
2851 is used and therefore @code{updatedb} and @code{locate} will both
2852 correctly handle file names containing newlines.  If the @code{sort}
2853 command lacks support for this, the list of files is delimited with
2854 the newline character, meaning that parts of file names containing
2855 newlines will be incorrectly sorted.  This can result in both
2856 incorrect matches and incorrect failures to match.
2858 On the other hand, if you are using the old database format, file
2859 names with embedded newlines are not correctly handled.  There is no
2860 technical limitation which enforces this, it's just that the
2861 @code{bigram} program has not been updated to support lists of file
2862 names separated by nulls.
2864 So, if you are using the new database format (this is the default) and
2865 your system uses GNU @code{sort}, newlines will be correctly handled
2866 at all times.  Otherwise, newlines may not be correctly handled.
2868 @node File Permissions
2869 @chapter File Permissions
2871 @include perm.texi
2873 @include getdate.texi
2875 @node Reference
2876 @chapter Reference
2878 Below are summaries of the command line syntax for the programs
2879 discussed in this manual.
2881 @menu
2882 * Invoking find::
2883 * Invoking locate::
2884 * Invoking updatedb::
2885 * Invoking xargs::
2886 * Regular Expressions::
2887 * Environment Variables::
2888 @end menu
2890 @node Invoking find
2891 @section Invoking @code{find}
2893 @example
2894 find @r{[-H] [-L] [-P] [-D @var{debugoptions}] [-O@var{level}]} @r{[}@var{file}@dots{}@r{]} @r{[}@var{expression}@r{]}
2895 @end example
2897 @code{find} searches the directory tree rooted at each file name
2898 @var{file} by evaluating the @var{expression} on each file it finds in
2899 the tree.
2901 The command line may begin with the @samp{-H}, @samp{-L}, @samp{-P},
2902 @samp{-D} and @samp{-O} options.  These are followed by a list of
2903 files or directories that should be searched.  If no files to search
2904 are specified, the current directory (@file{.}) is used.
2906 This list of files to search is followed by a list of expressions
2907 describing the files we wish to search for.  The first part of the
2908 expression is recognised by the fact that it begins with @samp{-}
2909 followed by some other letters (for example @samp{-print}), or is
2910 either @samp{(} or @samp{!}.  Any arguments after it are the rest of
2911 the expression.  
2913 If no expression is given, the expression @samp{-print} is used.
2915 The @code{find} command exits with status zero if all files matched
2916 are processed successfully, greater than zero if errors occur.
2918 The @code{find} program also recognises two options for administrative
2919 use:
2921 @table @samp
2922 @item --help
2923 Print a summary of the command line usage and exit.
2924 @item --version
2925 Print the version number of @code{find} and exit.
2926 @end table
2928 The @samp{-version} option is a synonym for @samp{--version}
2931 @menu
2932 * Filesystem Traversal Options::
2933 * Warning Messages::
2934 * Optimisation Options::
2935 * Debug Options::
2936 * Find Expressions::
2937 @end menu
2939 @node Filesystem Traversal Options
2940 @subsection Filesystem Traversal Options
2942 The options @samp{-H}, @samp{-L} or @samp{-P} may be specified at the
2943 start of the command line (if none of these is specified, @samp{-P} is
2944 assumed).  If you specify more than one of these options, the last one
2945 specified takes effect (but note that the @samp{-follow} option is
2946 equivalent to @samp{-L}).  
2948 @table @code
2949 @item -P
2950 Never follow symbolic links (this is the default), except in the case
2951 of the @samp{-xtype} predicate.
2952 @item -L
2953 Always follow symbolic links, except in the case of the @samp{-xtype}
2954 predicate.
2955 @item -H
2956 Follow symbolic links specified in the list of files to search, or
2957 which are otherwise specified on the command line.
2958 @end table
2960 If @code{find} would follow a symbolic link, but cannot for any reason
2961 (for example, because it has insufficient permissions or the link is
2962 broken), it falls back on using the properties of the symbolic link
2963 itself.  @ref{Symbolic Links} for a more complete description of how
2964 symbolic links are handled.
2966 @node Warning Messages
2967 @subsection Warning Messages
2969 If there is an error on the @code{find} command line, an error message
2970 is normally issued.  However, there are some usages that are
2971 inadvisable but which @code{find} should still accept.  Under these
2972 circumstances, @code{find} may issue a warning message.  By default,
2973 warnings are enabled only if @code{find} is being run interactively
2974 (specifically, if the standard input is a terminal).  Warning messages
2975 can be controlled explicitly by the use of options on the command
2976 line:
2978 @table @code
2979 @item -warn
2980 Issue warning messages where appropriate.
2981 @item -nowarn
2982 Do not issue warning messages.
2983 @end table
2985 These options take effect at the point on the command line where they
2986 are specified.  Therefore it's not useful to specify @samp{-nowarn} at
2987 the end of the command line.  The warning messages affected by the
2988 above options are triggered by:
2990 @itemize @minus
2991 @item
2992 Use of the @samp{-d} option which is deprecated; please use
2993 @samp{-depth} instead, since the latter is POSIX-compliant.
2994 @item
2995 Use of the @samp{-ipath} option which is deprecated; please use
2996 @samp{-iwholename} instead.
2997 @item
2998 Specifying an option (for example @samp{-mindepth}) after a non-option
2999 (for example @samp{-type} or @samp{-print}) on the command line.
3000 @item
3001 Use of the @samp{-name} or @samp{-iname} option with a slash character
3002 in the pattern.  Since the name predicates only compare against the
3003 basename of the visited files, the only file that can match a slash is
3004 the root directory itself.
3005 @end itemize
3007 The default behaviour above is designed to work in that way so that
3008 existing shell scripts don't generate spurious errors, but people will
3009 be made aware of the problem.
3011 Some warning messages are issued for less common or more serious
3012 problems, and consequently cannot be turned off:
3014 @itemize @minus
3015 @item
3016 Use of an unrecognised backslash escape sequence with @samp{-fprintf}
3017 @item
3018 Use of an unrecognised formatting directive with @samp{-fprintf}
3019 @end itemize
3021 @node Optimisation Options
3022 @subsection Optimisation Options
3024 The @samp{-O@var{level}} option sets @code{find}'s optimisation level
3025 to @var{level}.  The default optimisation level is 1.
3027 At certain optimisation levels, @code{find} reorders tests to speed up
3028 execution while preserving the overall effect; that is, predicates
3029 with side effects are not reordered relative to each other.  The
3030 optimisations performed at each optimisation level are as follows.
3032 @table @samp
3033 @item 0
3034 Currently equivalent to optimisation level 1.
3036 @item 1
3037 This is the default optimisation level and corresponds to the
3038 traditional behaviour.  Expressions are reordered so that tests based
3039 only on the names of files (for example@samp{ -name} and
3040 @samp{-regex}) are performed first.
3042 @item 2 
3043 Any @samp{-type} or @samp{-xtype} tests are performed after any tests
3044 based only on the names of files, but before any tests that require
3045 information from the inode.  On many modern versions of Unix, file
3046 types are returned by @code{readdir()} and so these predicates are
3047 faster to evaluate than predicates which need to stat the file first.
3049 @item 3 
3050 At this optimisation level, the full cost-based query optimiser is
3051 enabled.  The order of tests is modified so that cheap (i.e., fast)
3052 tests are performed first and more expensive ones are performed later,
3053 if necessary.  Within each cost band, predicates are evaluated earlier
3054 or later according to whether they are likely to succeed or not.  For
3055 @samp{-o}, predicates which are likely to succeed are evaluated
3056 earlier, and for @samp{-a}, predicates which are likely to fail are
3057 evaluated earlier.
3058 @end table
3061 @node Debug Options
3062 @subsection Debug Options
3064 The @samp{-D} option makes @code{find} produce diagnostic output.
3065 Much of the information is useful only for diagnosing problems, and so
3066 most people will not find this option helpful.
3068 The list of debug options should be comma separated.  Compatibility of
3069 the debug options is not guaranteed between releases of findutils.
3070 For a complete list of valid debug options, see the output of
3071 @code{find -D help}.  Valid debug options include:
3072 @table @samp
3073 @item help
3074 Explain the debugging options.
3075 @item tree   
3076 Show the expression tree in its original and optimised form.
3077 @item stat   
3078 Print messages as files are examined with the stat and lstat system
3079 calls.  The find program tries to minimise such calls.
3080 @item opt    
3081 Prints diagnostic information relating to the optimisation of the
3082 expression tree; see the @samp{-O} option.
3083 @item rates
3084 Prints a summary indicating how often each predicate succeeded or
3085 failed.
3086 @end table
3088 @node Find Expressions
3089 @subsection Find Expressions
3091 The final part of the @code{find} command line is a list of
3092 expressions.  @xref{Primary Index}, for a summary of all of the tests,
3093 actions, and options that the expression can contain.  If the
3094 expression is missing, @samp{-print} is assumed.
3096 @node Invoking locate
3097 @section Invoking @code{locate}
3099 @example
3100 locate @r{[}@var{option}@dots{}@r{]} @var{pattern}@dots{}
3101 @end example
3103 For each @var{pattern} given @code{locate} searches one or more file
3104 name databases returning each match of @var{pattern}.
3106 For each @var{pattern} given @code{locate} searches one or more file
3107 name databases returning each match of @var{pattern}.
3109 @table @code
3110 @item --all
3111 @itemx -A
3112 Print only names which match all non-option arguments, not those
3113 matching one or more non-option arguments.
3115 @item --basename
3116 @itemx -b
3117 The specified pattern is matched against just the last component of
3118 the name of a file in the @code{locate} database.  This last
3119 component is also called the ``base name''.  For example, the base
3120 name of @file{/tmp/mystuff/foo.old.c} is @file{foo.old.c}.  If the
3121 pattern contains metacharacters, it must match the base name exactly.
3122 If not, it must match part of the base name.
3124 @item --count
3125 @itemx -c
3126 Instead of printing the matched file names, just print the total
3127 number of matches found, unless @samp{--print} (@samp{-p}) is also
3128 present.
3131 @item --database=@var{path}
3132 @itemx -d @var{path}
3133 Instead of searching the default @code{locate} database
3134 @file{@value{LOCATE_DB}}, @code{locate} searches the file
3135 name databases in @var{path}, which is a colon-separated list of
3136 database file names.  You can also use the environment variable
3137 @code{LOCATE_PATH} to set the list of database files to search.  The
3138 option overrides the environment variable if both are used.  Empty
3139 elements in @var{path} (that is, a leading or trailing colon, or two
3140 colons in a row) are taken to stand for the default database.
3141 A database can be supplied on stdin, using @samp{-} as an element
3142 of @samp{path}. If more than one element of @samp{path} is @samp{-},
3143 later instances are ignored (but a warning message is printed).
3145 @item --existing
3146 @itemx -e
3147 Only print out such names which currently exist (instead of such names
3148 which existed when the database was created).  Note that this may slow
3149 down the program a lot, if there are many matches in the database.
3150 The way in which broken symbolic links are treated is affected by the
3151 @samp{-L}, @samp{-P} and @samp{-H} options.  Please note that it is
3152 possible for the file to be deleted after @code{locate} has checked
3153 that it exists, but before you use it.  This option is automatically
3154 turned on when reading an @code{slocate} database in secure mode
3155 (@pxref{slocate Database Format}).
3157 @item --non-existing
3158 @itemx -E
3159 Only print out such names which currently do not exist (instead of
3160 such names which existed when the database was created).  Note that
3161 this may slow down the program a lot, if there are many matches in the
3162 database.  The way in which broken symbolic links are treated is
3163 affected by the @samp{-L}, @samp{-P} and @samp{-H} options.  Please
3164 note that @code{locate} checks that the file does not exist, but a
3165 file of the same name might be created after @code{locate}'s check but
3166 before you read @code{locate}'s output.
3168 @item --follow
3169 @itemx -L
3170 If testing for the existence of files (with the @samp{-e} or @samp{-E}
3171 options), consider broken symbolic links to be non-existing.  This is
3172 the default behaviour.  
3174 @item --nofollow
3175 @itemx -P
3176 @itemx -H
3177 If testing for the existence of files (with the @samp{-e} or @samp{-E}
3178 options), treat broken symbolic links as if they were existing files.
3179 The @samp{-H} form of this option is provided purely for similarity
3180 with @code{find}; the use of @samp{-P} is recommended over @samp{-H}.
3182 @item --ignore-case
3183 @itemx -i
3184 Ignore case distinctions in both the pattern and the file names.
3186 @item --limit=N
3187 @itemx -l N
3188 Limit the number of results printed to N.  When used with the
3189 @samp{--count} option, the value printed will never be larger than
3190 this limit.
3191 @item --max-database-age=D
3192 Normally, @code{locate} will issue a warning message when it searches
3193 a database which is more than 8 days old.  This option changes that
3194 value to something other than 8.  The effect of specifying a negative
3195 value is undefined.
3196 @item --mmap
3197 @itemx -m
3198 Accepted but does nothing.  The option is supported only to provide
3199 compatibility with BSD's @code{locate}.
3201 @item --null
3202 @itemx -0
3203 Results are separated with the ASCII NUL character rather than the
3204 newline character.  To get the full benefit of the use of this option,
3205 use the new @code{locate} database format (that is the default
3206 anyway).
3208 @item --print
3209 @itemx -p
3210 Print search results when they normally would not, because of the
3211 presence of @samp{--statistics} (@samp{-S}) or @samp{--count}
3212 (@samp{-c}).
3214 @item --wholename
3215 @itemx -w
3216 The specified pattern is matched against the whole name of the file in
3217 the @code{locate} database.  If the pattern contains metacharacters,
3218 it must match exactly.  If not, it must match part of the whole file
3219 name.  This is the default behaviour.
3221 @item --regex
3222 @itemx -r
3223 Instead of using substring or shell glob matching, the pattern
3224 specified on the command line is understood to be a regular
3225 expression.  GNU Emacs-style regular expressions are assumed unless
3226 the @samp{--regextype} option is also given.  File names from the
3227 @code{locate} database are matched using the specified regular
3228 expression.  If the @samp{-i} flag is also given, matching is
3229 case-insensitive.  Matches are performed against the whole path name,
3230 and so by default a pathname will be matched if any part of it matches
3231 the specified regular expression.  The regular expression may use
3232 @samp{^} or @samp{$} to anchor a match at the beginning or end of a
3233 pathname.
3235 @item --regextype
3236 This option changes the regular expression syntax and behaviour used
3237 by the @samp{--regex} option.  @ref{Regular Expressions} for more
3238 information on the regular expression dialects understood by GNU
3239 findutils.
3241 @item --stdio
3242 @itemx -s
3243 Accepted but does nothing.  The option is supported only to provide
3244 compatibility with BSD's @code{locate}.
3246 @item --statistics
3247 @itemx -S
3248 Print some summary information for each @code{locate} database.  No
3249 search is performed unless non-option arguments are given.
3250 Although the BSD version of locate also has this option, the format of the
3251 output is different.
3253 @item --help
3254 Print a summary of the command line usage for @code{locate} and exit.
3256 @item --version
3257 Print the version number of @code{locate} and exit.
3258 @end table
3260 @node Invoking updatedb
3261 @section Invoking @code{updatedb}
3263 @example
3264 updatedb @r{[}@var{option}@dots{}@r{]}
3265 @end example
3267 @code{updatedb} creates and updates the database of file names used by
3268 @code{locate}.  @code{updatedb} generates a list of files similar to
3269 the output of @code{find} and then uses utilities for optimizing the
3270 database for performance.  @code{updatedb} is often run periodically
3271 as a @code{cron} job and configured with environment variables or
3272 command options.  Typically, operating systems have a shell script
3273 that ``exports'' configurations for variable definitions and uses
3274 another shell script that ``sources'' the configuration file into the
3275 environment and then executes @code{updatedb} in the environment.
3277 @code{updatedb} creates and updates the database of file names used by
3278 @code{locate}.  @code{updatedb} generates a list of files similar to
3279 the output of @code{find} and then uses utilities for optimizing the
3280 database for performance.  @code{updatedb} is often run periodically
3281 as a @code{cron} job and configured with environment variables or
3282 command options.  Typically, operating systems have a shell script
3283 that ``exports'' configurations for variable definitions and uses
3284 another shell script that ``sources'' the configuration file into the
3285 environment and then executes @code{updatedb} in the environment.
3287 @table @code
3288 @item --findoptions='@var{OPTION}@dots{}'
3289 Global options to pass on to @code{find}.
3290 The environment variable @code{FINDOPTIONS} also sets this value.
3291 Default is none.
3293 @item --localpaths='@var{path}@dots{}'
3294 Non-network directories to put in the database.
3295 Default is @file{/}.
3297 @item --netpaths='@var{path}@dots{}'
3298 Network (NFS, AFS, RFS, etc.) directories to put in the database.
3299 The environment variable @code{NETPATHS} also sets this value.
3300 Default is none.
3302 @item --prunepaths='@var{path}@dots{}'
3303 Directories to omit from the database, which would otherwise be
3304 included.  The environment variable @code{PRUNEPATHS} also sets this
3305 value.  Default is @file{/tmp /usr/tmp /var/tmp /afs}.  The paths are
3306 used as regular expressions (with @code{find ... -regex}, so you need
3307 to specify these paths in the same way that @code{find} will encounter
3308 them.  This means for example that the paths must not include trailing
3309 slashes.
3311 @item --prunefs='@var{path}@dots{}'
3312 Filesystems to omit from the database, which would otherwise be
3313 included.  Note that files are pruned when a filesystem is reached;
3314 Any filesystem mounted under an undesired filesystem will be ignored.
3315 The environment variable @code{PRUNEFS} also sets this value.  Default
3316 is @file{nfs NFS proc}.
3318 @item --output=@var{dbfile}
3319 The database file to build.  The default is system-dependent, but
3320 when this document was formatted it was @file{@value{LOCATE_DB}}.
3322 @item --localuser=@var{user}
3323 The user to search the non-network directories as, using @code{su}.
3324 Default is to search the non-network directories as the current user.
3325 You can also use the environment variable @code{LOCALUSER} to set this user.
3327 @item --netuser=@var{user}
3328 The user to search network directories as, using @code{su}.  Default
3329 @code{user} is @code{daemon}.  You can also use the environment variable
3330 @code{NETUSER} to set this user.
3332 @item --old-format
3333 Generate a @code{locate} database in the old format, for compatibility
3334 with versions of @code{locate} other than GNU @code{locate}.  Using
3335 this option means that @code{locate} will not be able to properly
3336 handle non-ASCII characters in file names (that is, file names
3337 containing characters which have the eighth bit set, such as many of
3338 the characters from the ISO-8859-1 character set).  @xref{Database
3339 Formats}, for a detailed description of the supported database
3340 formats.
3342 @item --dbformat=@var{FORMAT}
3343 Generate the locate database in format @code{FORMAT}.  Supported
3344 database formats include @code{LOCATE02} (which is the default),
3345 @code{old} and @code{slocate}.  The @code{old} format exists for
3346 compatibility with implementations of @code{locate} on other Unix
3347 systems.  The @code{slocate} format exists for compatibility with
3348 @code{slocate}.  @xref{Database Formats}, for a detailed description
3349 of each format.
3351 @item --help
3352 Print a summary of the command line usage and exit.
3353 @item --version
3354 Print the version number of @code{updatedb} and exit.
3355 @end table
3357 @node Invoking xargs
3358 @section Invoking @code{xargs}
3360 @example
3361 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
3362 @end example
3364 @code{xargs} exits with the following status:
3366 @table @asis
3367 @item 0
3368 if it succeeds
3369 @item 123
3370 if any invocation of the command exited with status 1-125
3371 @item 124
3372 if the command exited with status 255
3373 @item 125
3374 if the command is killed by a signal
3375 @item 126
3376 if the command cannot be run
3377 @item 127
3378 if the command is not found
3379 @item 1
3380 if some other error occurred.
3381 @end table
3383 Exit codes greater than 128 are used by the shell to indicate that 
3384 a program died due to a fatal signal.
3385   
3386 @table @code
3387 @item --arg-file@r{=@var{inputfile}}
3388 @itemx -a @r{@var{inputfile}}
3389 Read names from the file @var{inputfile} instead of standard input.
3390 If you use this option, the standard input stream remains unchanged
3391 when commands are run. Otherwise, stdin is redirected from
3392 @file{/dev/null}.
3394 @item --null
3395 @itemx -0
3396 Input file names are terminated by a null character instead of by
3397 whitespace, and any quotes and backslash characters are not considered
3398 special (every character is taken literally).  Disables the end of
3399 file string, which is treated like any other argument.
3401 @item --delimiter @var{delim}
3402 @itemx -d @var{delim}
3404 Input file names are terminated by the specified character @var{delim}
3405 instead of by whitespace, and any quotes and backslash characters are
3406 not considered special (every character is taken literally).  Disables
3407 the end of file string, which is treated like any other argument.
3409 The specified delimiter may be a single character, a C-style character
3410 escape such as @samp{\n}, or an octal or hexadecimal escape code.
3411 Octal and hexadecimal escape codes are understood as for the
3412 @code{printf} command.  Multibyte characters are not supported.
3415 @item -E @var{eof-str}
3416 @itemx --eof@r{[}=@var{eof-str}@r{]}
3417 @itemx -e@r{[}@var{eof-str}@r{]}
3418 Set the end of file string to @var{eof-str}.  If the end of file
3419 string occurs as a line of input, the rest of the input is ignored.
3420 If @var{eof-str} is omitted (@samp{-e}) or blank (either @samp{-e} or
3421 @samp{-E}), there is no end of file string.  The @samp{-e} form of
3422 this option is deprecated in favour of the POSIX-compliant @samp{-E}
3423 option, which you should use instead.  As of GNU xargs version 4.2.9,
3424 the default behaviour of xargs is not to have a logical end-of-file
3425 marker.  The POSIX standard (IEEE Std 1003.1, 2004 Edition) allows
3426 this.
3428 @item --help
3429 Print a summary of the options to @code{xargs} and exit.
3431 @item -I @var{replace-str}
3432 @itemx --replace@r{[}=@var{replace-str}@r{]}
3433 @itemx -i@r{[}@var{replace-str}@r{]}
3434 Replace occurrences of @var{replace-str} in the initial arguments with
3435 names read from standard input.  Also, unquoted blanks do not
3436 terminate arguments; instead, the input is split at newlines only.  If
3437 @var{replace-str} is omitted (omitting it is allowed only for
3438 @samp{-i}), it defaults to @samp{@{@}} (like for @samp{find -exec}).
3439 Implies @samp{-x} and @samp{-l 1}.  The @samp{-i} option is deprecated
3440 in favour of the @samp{-I} option.
3442 @item -L @var{max-lines}
3443 @itemx --max-lines@r{[}=@var{max-lines}@r{]}
3444 @itemx -l@r{[}@var{max-lines}@r{]}
3445 Use at most @var{max-lines} non-blank input lines per command line.
3446 For @samp{-l}, @var{max-lines} defaults to 1 if omitted.  For
3447 @samp{-L}, the argument is mandatory.  Trailing blanks cause an input
3448 line to be logically continued on the next input line, for the purpose
3449 of counting the lines.  Implies @samp{-x}.  The @samp{-l} form of this
3450 option is deprecated in favour of the POSIX-compliant @samp{-L}
3451 option.
3453 @item --max-args=@var{max-args}
3454 @itemx -n @var{max-args}
3455 Use at most @var{max-args} arguments per command line.  Fewer than
3456 @var{max-args} arguments will be used if the size (see the @samp{-s}
3457 option) is exceeded, unless the @samp{-x} option is given, in which
3458 case @code{xargs} will exit.
3460 @item --interactive
3461 @itemx -p
3462 Prompt the user about whether to run each command line and read a line
3463 from the terminal.  Only run the command line if the response starts
3464 with @samp{y} or @samp{Y}.  Implies @samp{-t}.
3466 @item --no-run-if-empty
3467 @itemx -r
3468 If the standard input is completely empty, do not run the
3469 command.  By default, the command is run once even if there is no
3470 input.
3472 @item --max-chars=@var{max-chars}
3473 @itemx -s @var{max-chars}
3474 Use at most @var{max-chars} characters per command line, including the
3475 command, initial arguments and any terminating nulls at the ends of
3476 the argument strings.
3478 @item --show-limits
3479 Display the limits on the command-line length which are imposed by the
3480 operating system, @code{xargs}' choice of buffer size and the
3481 @samp{-s} option.  Pipe the input from @file{/dev/null} (and perhaps
3482 specify @samp{--no-run-if-empty}) if you don't want @code{xargs} to do
3483 anything.
3485 @item --verbose
3486 @itemx -t
3487 Print the command line on the standard error output before executing
3490 @item --version
3491 Print the version number of @code{xargs} and exit.
3493 @item --exit
3494 @itemx -x
3495 Exit if the size (see the @samp{-s} option) is exceeded.
3498 @item --max-procs=@var{max-procs}
3499 @itemx -P @var{max-procs}
3500 Run simultaneously up to @var{max-procs} processes at once; the default is 1.  If
3501 @var{max-procs} is 0, @code{xargs} will run as many processes as
3502 possible simultaneously.
3503 @end table
3506 @node Regular Expressions
3507 @section Regular Expressions
3509 The @samp{-regex} and @samp{-iregex} tests of @code{find} allow
3510 matching by regular expression, as does the @samp{--regex} option of
3511 @code{locate}.  There are many different types of Regular Expression,
3512 but the type used by @code{find} and @code{locate} is the same as is
3513 used in GNU Emacs.  Both programs provide an option which allows you
3514 to select an alternative regular expression syntax; for @code{find}
3515 this is the @samp{-regextype} option, and for @code{locate} this is
3516 the @samp{--regextype} option.
3518 These options take a single argument, which indicates the specific
3519 regular expression syntax and behaviour that should be used.  This
3520 should be one of the following:
3522 @include regexprops.texi
3524 @node Environment Variables
3525 @section Environment Variables
3526 @table @var
3527 @item LANG
3528 Provides a default value for the internationalisation variables that
3529 are unset or null.
3530 @item LC_ALL
3531 If set to a non-empty string value, override the values of all the
3532 other internationalisation variables.
3533 @item LC_COLLATE
3534 The POSIX standard specifies that this variable affects the pattern
3535 matching to be used for the `\-name' option.  GNU find uses the
3536 GNU version of the @code{fnmatch} library function.
3538 POSIX also specifies that the `LC_COLLATE' environment 
3539 variable affects the interpretation of the user's response to the 
3540 query issued by `\-ok', but this is not the case for GNU find.
3541 @item LC_CTYPE 
3542 This variable affects the treatment of character classes used with 
3543 the @samp{-name} test, if the system's 
3544 @code{fnmatch} library function supports this.   It has no effect on the behaviour 
3545 of the @samp{-ok} expression.
3546 @item LC_MESSAGES
3547 Determines the locale to be used for internationalised messages.
3548 @item NLSPATH
3549 Determines the location of the internationalisation message catalogues.
3550 @item PATH
3551 Affects the directories which are searched to find the executables
3552 invoked by @samp{-exec}, @samp{-execdir} @samp{-ok} and @samp{-okdir}.
3553 If the @var{PATH} environment variable includes the current directory
3554 (by explicitly including @samp{.} or by having an empty element), and
3555 the find command line includes @samp{-execdir} or @samp{-okdir},
3556 @code{find} will refuse to run.  @xref{Security Considerations}, for a
3557 more detailed discussion of security matters.
3559 @item POSIXLY_CORRECT 
3560 Determines the block size used by @samp{-ls} and @samp{-fls}.  
3561 If @var{POSIXLY_CORRECT} is set, blocks are units of 512 bytes.  Otherwise
3562 they are units of 1024 bytes.
3564 @item TZ 
3565 Affects the time zone used for some of the time-related format
3566 directives of @samp{-printf} and @samp{-fprintf}.
3567 @end table
3571 @node Common Tasks
3572 @chapter Common Tasks
3574 The sections that follow contain some extended examples that both give
3575 a good idea of the power of these programs, and show you how to solve
3576 common real-world problems.
3578 @menu
3579 * Viewing And Editing::
3580 * Archiving::
3581 * Cleaning Up::
3582 * Strange File Names::
3583 * Fixing Permissions::
3584 * Classifying Files::
3585 @end menu
3587 @node Viewing And Editing
3588 @section Viewing And Editing
3590 To view a list of files that meet certain criteria, simply run your
3591 file viewing program with the file names as arguments.  Shells
3592 substitute a command enclosed in backquotes with its output, so the
3593 whole command looks like this:
3595 @example
3596 less `find /usr/include -name '*.h' | xargs grep -l mode_t`
3597 @end example
3599 @noindent
3600 You can edit those files by giving an editor name instead of a file
3601 viewing program:
3603 @example
3604 emacs `find /usr/include -name '*.h' | xargs grep -l mode_t`
3605 @end example
3607 Because there is a limit to the length of any individual command line,
3608 there is a limit to the number of files that can be handled in this
3609 way.  We can get around this difficulty by using xargs like this:
3611 @example
3612 find /usr/include -name '*.h' | xargs grep -l mode_t > todo
3613 xargs --arg-file=todo emacs
3614 @end example
3616 Here, @code{xargs} will run @code{emacs} as many times as necessary to
3617 visit all of the files listed in the file @file{todo}.
3619 @node Archiving
3620 @section Archiving
3622 You can pass a list of files produced by @code{find} to a file
3623 archiving program.  GNU @code{tar} and @code{cpio} can both read lists
3624 of file names from the standard input---either delimited by nulls (the
3625 safe way) or by blanks (the lazy, risky default way).  To use
3626 null-delimited names, give them the @samp{--null} option.  You can
3627 store a file archive in a file, write it on a tape, or send it over a
3628 network to extract on another machine.
3630 One common use of @code{find} to archive files is to send a list of
3631 the files in a directory tree to @code{cpio}.  Use @samp{-depth} so if
3632 a directory does not have write permission for its owner, its contents
3633 can still be restored from the archive since the directory's
3634 permissions are restored after its contents.  Here is an example of
3635 doing this using @code{cpio}; you could use a more complex @code{find}
3636 expression to archive only certain files.
3638 @example
3639 find . -depth -print0 |
3640   cpio --create --null --format=crc --file=/dev/nrst0
3641 @end example
3643 You could restore that archive using this command:
3645 @example
3646 cpio --extract --null --make-dir --unconditional \
3647   --preserve --file=/dev/nrst0
3648 @end example
3650 Here are the commands to do the same things using @code{tar}:
3652 @example
3653 find . -depth -print0 |
3654   tar --create --null --files-from=- --file=/dev/nrst0
3656 tar --extract --null --preserve-perm --same-owner \
3657   --file=/dev/nrst0
3658 @end example
3660 @c Idea from Rick Sladkey.
3661 Here is an example of copying a directory from one machine to another:
3663 @example
3664 find . -depth -print0 | cpio -0o -Hnewc |
3665   rsh @var{other-machine} "cd `pwd` && cpio -i0dum"
3666 @end example
3668 @node Cleaning Up
3669 @section Cleaning Up
3671 @c Idea from Jim Meyering.
3672 This section gives examples of removing unwanted files in various
3673 situations.  Here is a command to remove the CVS backup files created
3674 when an update requires a merge:
3676 @example
3677 find . -name '.#*' -print0 | xargs -0r rm -f
3678 @end example
3680 The command above works, but the following is safer:
3682 @example
3683 find . -name '.#*' -depth -delete
3684 @end example
3686 @c Idea from Franc,ois Pinard.
3687 You can run this command to clean out your clutter in @file{/tmp}.
3688 You might place it in the file your shell runs when you log out
3689 (@file{.bash_logout}, @file{.logout}, or @file{.zlogout}, depending on
3690 which shell you use).
3692 @example
3693 find /tmp -depth -user "$LOGNAME" -type f -delete
3694 @end example
3696 If your @code{find} command removes directories, you may find that
3697 you get a spurious error message when @code{find} tries to recurse
3698 into a directory that has now been removed.  Using the @samp{-depth}
3699 option will normally resolve this problem.
3701 @c Idea from Noah Friedman.
3702 To remove old Emacs backup and auto-save files, you can use a command
3703 like the following.  It is especially important in this case to use
3704 null-terminated file names because Emacs packages like the VM mailer
3705 often create temporary file names with spaces in them, like
3706 @file{#reply to David J. MacKenzie<1>#}.
3708 @example
3709 find ~ \( -name '*~' -o -name '#*#' \) -print0 |
3710   xargs --no-run-if-empty --null rm -vf
3711 @end example
3713 Removing old files from @file{/tmp} is commonly done from @code{cron}:
3715 @c Idea from Kaveh Ghazi.
3716 @example
3717 find /tmp /var/tmp -not -type d -mtime +3 -delete
3718 find /tmp /var/tmp -depth -mindepth 1 -type d -empty -delete
3719 @end example
3721 The second @code{find} command above uses @samp{-depth} so it cleans
3722 out empty directories depth-first, hoping that the parents become
3723 empty and can be removed too.  It uses @samp{-mindepth} to avoid
3724 removing @file{/tmp} itself if it becomes totally empty.
3726 @node Strange File Names
3727 @section Strange File Names
3729 @c Idea from:
3730 @c From: tmatimar@isgtec.com (Ted Timar)
3731 @c Newsgroups: comp.unix.questions,comp.unix.shell,comp.answers,news.answers
3732 @c Subject: Unix - Frequently Asked Questions (2/7) [Frequent posting]
3733 @c Subject: How do I remove a file with funny characters in the filename ?
3734 @c Date: Thu Mar 18 17:16:55 EST 1993
3735 @code{find} can help you remove or rename a file with strange
3736 characters in its name.  People are sometimes stymied by files whose
3737 names contain characters such as spaces, tabs, control characters, or
3738 characters with the high bit set.  The simplest way to remove such
3739 files is:
3741 @example
3742 rm -i @var{some*pattern*that*matches*the*problem*file}
3743 @end example
3745 @code{rm} asks you whether to remove each file matching the given
3746 pattern.  If you are using an old shell, this approach might not work
3747 if the file name contains a character with the high bit set; the shell
3748 may strip it off.  A more reliable way is:
3750 @example
3751 find . -maxdepth 1 @var{tests} -okdir rm '@{@}' \;
3752 @end example
3754 @noindent
3755 where @var{tests} uniquely identify the file.  The @samp{-maxdepth 1}
3756 option prevents @code{find} from wasting time searching for the file
3757 in any subdirectories; if there are no subdirectories, you may omit
3758 it.  A good way to uniquely identify the problem file is to figure out
3759 its inode number; use
3761 @example
3762 ls -i
3763 @end example
3765 Suppose you have a file whose name contains control characters, and
3766 you have found that its inode number is 12345.  This command prompts
3767 you for whether to remove it:
3769 @example
3770 find . -maxdepth 1 -inum 12345 -okdir rm -f '@{@}' \;
3771 @end example
3773 If you don't want to be asked, perhaps because the file name may
3774 contain a strange character sequence that will mess up your screen
3775 when printed, then use @samp{-execdir} instead of @samp{-okdir}.
3777 If you want to rename the file instead, you can use @code{mv} instead
3778 of @code{rm}:
3780 @example
3781 find . -maxdepth 1 -inum 12345 -okdir mv '@{@}' @var{new-file-name} \;
3782 @end example
3784 @node Fixing Permissions
3785 @section Fixing Permissions
3787 Suppose you want to make sure that everyone can write to the
3788 directories in a certain directory tree.  Here is a way to find
3789 directories lacking either user or group write permission (or both),
3790 and fix their permissions:
3792 @example
3793 find . -type d -not -perm -ug=w | xargs chmod ug+w
3794 @end example
3796 @noindent
3797 You could also reverse the operations, if you want to make sure that
3798 directories do @emph{not} have world write permission.
3800 @node Classifying Files
3801 @section Classifying Files
3803 @c Idea from:
3804 @c From: martin@mwtech.UUCP (Martin Weitzel)
3805 @c Newsgroups: comp.unix.wizards,comp.unix.questions
3806 @c Subject: Advanced usage of 'find' (Re: Unix security automating script)
3807 @c Date: 22 Mar 90 15:05:19 GMT
3808 If you want to classify a set of files into several groups based on
3809 different criteria, you can use the comma operator to perform multiple
3810 independent tests on the files.  Here is an example:
3812 @example
3813 find / -type d \( -perm -o=w -fprint allwrite , \
3814   -perm -o=x -fprint allexec \)
3816 echo "Directories that can be written to by everyone:"
3817 cat allwrite
3818 echo ""
3819 echo "Directories with search permissions for everyone:"
3820 cat allexec
3821 @end example
3823 @code{find} has only to make one scan through the directory tree
3824 (which is one of the most time consuming parts of its work).
3826 @node Worked Examples
3827 @chapter Worked Examples
3829 The tools in the findutils package, and in particular @code{find},
3830 have a large number of options.  This means that quite often,
3831 there is more than one way to do things.  Some of the options
3832 and facilities only exist for compatibility with other tools, and
3833 findutils provides improved ways of doing things.
3835 This chapter describes a number of useful tasks that are commonly
3836 performed, and compares the different ways of achieving them.
3838 @menu
3839 * Deleting Files::
3840 * Copying A Subset of Files::
3841 * Updating A Timestamp File::
3842 @end menu
3844 @node Deleting Files
3845 @section Deleting Files
3847 One of the most common tasks that @code{find} is used for is locating
3848 files that can be deleted.  This might include:
3850 @itemize
3851 @item 
3852 Files last modified more than 3 years ago which haven't been accessed
3853 for at least 2 years
3854 @item
3855 Files belonging to a certain user
3856 @item
3857 Temporary files which are no longer required
3858 @end itemize
3860 This example concentrates on the actual deletion task rather than on
3861 sophisticated ways of locating the files that need to be deleted.
3862 We'll assume that the files we want to delete are old files underneath
3863 @file{/var/tmp/stuff}.
3865 @subsection The Traditional Way
3867 The traditional way to delete files in @file{/var/tmp/stuff} that have
3868 not been modified in over 90 days would have been:
3870 @smallexample
3871 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \;
3872 @end smallexample
3874 The above command uses @samp{-exec} to run the @code{/bin/rm} command
3875 to remove each file.  This approach works and in fact would have
3876 worked in Version 7 Unix in 1979.  However, there are a number of
3877 problems with this approach.
3880 The most obvious problem with the approach above is that it causes
3881 @code{find} to fork every time it finds a file that needs to delete,
3882 and the child process then has to use the @code{exec} system call to
3883 launch @code{/bin/rm}.   All this is quite inefficient.  If we are
3884 going to use @code{/bin/rm} to do this job, it is better to make it
3885 delete more than one file at a time.  
3887 The most obvious way of doing this is to use the shell's command
3888 expansion feature:
3890 @smallexample
3891 /bin/rm `find /var/tmp/stuff -mtime +90 -print`
3892 @end smallexample
3893 or you could use the more modern form
3894 @smallexample
3895 /bin/rm $(find /var/tmp/stuff -mtime +90 -print)
3896 @end smallexample
3898 The commands above are much more efficient than the first attempt.
3899 However, there is a problem with them.  The shell has a maximum
3900 command length which is imposed by the operating system (the actual
3901 limit varies between systems).  This means that while the command
3902 expansion technique will usually work, it will suddenly fail when
3903 there are lots of files to delete.  Since the task is to delete
3904 unwanted files, this is precisely the time we don't want things to go
3905 wrong.
3907 @subsection Making Use of xargs
3909 So, is there a way to be more efficient in the use of @code{fork()}
3910 and @code{exec()} without running up against this limit?
3911 Yes, we can be almost optimally efficient by making use
3912 of the @code{xargs} command.  The @code{xargs} command reads arguments
3913 from its standard input and builds them into command lines.  We can
3914 use it like this:
3916 @smallexample
3917 find /var/tmp/stuff -mtime +90 -print | xargs /bin/rm 
3918 @end smallexample
3920 For example if the files found by @code{find} are
3921 @file{/var/tmp/stuff/A}, 
3922 @file{/var/tmp/stuff/B} and 
3923 @file{/var/tmp/stuff/C} then @code{xargs} might issue the commands 
3925 @smallexample
3926 /bin/rm /var/tmp/stuff/A /var/tmp/stuff/B
3927 /bin/rm /var/tmp/stuff/C
3928 @end smallexample
3930 The above assumes that @code{xargs} has a very small maximum command
3931 line length.  The real limit is much larger but the idea is that
3932 @code{xargs} will run @code{/bin/rm} as many times as necessary to get
3933 the job done, given the limits on command line length.
3935 This usage of @code{xargs} is pretty efficient, and the @code{xargs}
3936 command is widely implemented (all modern versions of Unix offer it).
3937 So far then, the news is all good.  However, there is bad news too.
3939 @subsection Unusual characters in filenames
3941 Unix-like systems allow any characters to appear in file names with
3942 the exception of the ASCII NUL character and the backslash.
3943 Backslashes can occur in path names (as the directory separator) but
3944 not in the names of actual directory entries.  This means that the
3945 list of files that @code{xargs} reads could in fact contain white space
3946 characters --- spaces, tabs and newline characters.  Since by default,
3947 @code{xargs} assumes that the list of files it is reading uses white
3948 space as an argument separator, it cannot correctly handle the case
3949 where a filename actually includes white space.  This makes the
3950 default behaviour of @code{xargs} almost useless for handling
3951 arbitrary data.
3953 To solve this problem, GNU findutils introduced the @samp{-print0}
3954 action for @code{find}.  This uses the ASCII NUL character to separate
3955 the entries in the file list that it produces.  This is the ideal
3956 choice of separator since it is the only character that cannot appear
3957 within a path name.  The @samp{-0} option to @code{xargs} makes it
3958 assume that arguments are separated with ASCII NUL instead of white
3959 space.  It also turns off another misfeature in the default behaviour
3960 of @code{xargs}, which is that it pays attention to quote characters
3961 in its input.  Some versions of @code{xargs} also terminate when they
3962 see a lone @samp{_} in the input, but GNU @code{find} no longer does
3963 that (since it has become an optional behaviour in the Unix standard).
3965 So, putting @code{find -print0} together with @code{xargs -0} we get
3966 this command:
3968 @smallexample
3969 find /var/tmp/stuff -mtime +90 -print0 | xargs -0 /bin/rm 
3970 @end smallexample
3972 The result is an efficient way of proceeding that
3973 correctly handles all the possible characters that could appear in the
3974 list of files to delete.  This is good news.  However, there is, as
3975 I'm sure you're expecting, also more bad news.  The problem is that
3976 this is not a portable construct; although other versions of Unix
3977 (notably BSD-derived ones) support @samp{-print0}, it's not
3978 universal.  So, is there a more universal mechanism?
3980 @subsection Going back to -exec
3982 There is indeed a more universal mechanism, which is a slight
3983 modification to the @samp{-exec} action.  The normal @samp{-exec}
3984 action assumes that the command to run is terminated with a semicolon
3985 (the semicolon normally has to be quoted in order to protect it from
3986 interpretation as the shell command separator).  The SVR4 edition of
3987 Unix introduced a slight variation, which involves terminating the
3988 command with @samp{+} instead:
3990 @smallexample
3991 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \+
3992 @end smallexample
3994 The above use of @samp{-exec} causes @code{find} to build up a long
3995 command line and then issue it.  This can be less efficient than some
3996 uses of @code{xargs}; for example @code{xargs} allows new command
3997 lines to be built up while the previous command is still executing, and
3998 allows you to specify a number of commands to run in parallel.
3999 However, the @code{find @dots{} -exec @dots{} +} construct has the advantage
4000 of wide portability.  GNU findutils did not support @samp{-exec @dots{} +}
4001 until version 4.2.12; one of the reasons for this is that it already
4002 had the @samp{-print0} action in any case.
4005 @subsection A more secure version of -exec
4007 The command above seems to be efficient and portable.  However,
4008 within it lurks a security problem.  The problem is shared with
4009 all the commands we've tried in this worked example so far, too.  The
4010 security problem is a race condition; that is, if it is possible for
4011 somebody to manipulate the filesystem that you are searching while you
4012 are searching it, it is possible for them to persuade your @code{find}
4013 command to cause the deletion of a file that you can delete but they
4014 normally cannot.  
4016 The problem occurs because the @samp{-exec} action is defined by the
4017 @acronym{POSIX} standard to invoke its command with the same working directory
4018 as @code{find} had when it was started.  This means that the arguments
4019 which replace the @{@} include a relative path from @code{find}'s
4020 starting point down the file that needs to be deleted.  For example,
4022 @smallexample
4023 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \+
4024 @end smallexample
4026 might actually issue the command:
4028 @smallexample
4029 /bin/rm /var/tmp/stuff/A /var/tmp/stuff/B /var/tmp/stuff/passwd
4030 @end smallexample
4032 Notice the file @file{/var/tmp/stuff/passwd}.  Likewise, the command:
4034 @smallexample
4035 cd /var/tmp && find stuff -mtime +90 -exec /bin/rm @{@} \+
4036 @end smallexample
4038 might actually issue the command:
4040 @smallexample
4041 /bin/rm stuff/A stuff/B stuff/passwd
4042 @end smallexample
4044 If an attacker can rename @file{stuff} to something else (making use
4045 of their write permissions in @file{/var/tmp}) they can replace it
4046 with a symbolic link to @file{/etc}.  That means that the
4047 @code{/bin/rm} command will be invoked on @file{/etc/passwd}.  If you
4048 are running your @code{find} command as root, the attacker has just managed
4049 to delete a vital file.  All they needed to do to achieve this was
4050 replace a subdirectory with a symbolic link at the vital moment.
4052 There is however, a simple solution to the problem.  This is an action
4053 which works a lot like @code{-exec} but doesn't need to traverse a
4054 chain of directories to reach the file that it needs to work on.  This
4055 is the @samp{-execdir} action, which was introduced by the BSD family
4056 of operating systems.   The command,
4058 @smallexample
4059 find /var/tmp/stuff -mtime +90 -execdir /bin/rm @{@} \+
4060 @end smallexample
4062 might delete a set of files by performing these actions:
4064 @enumerate
4065 @item 
4066 Change directory to /var/tmp/stuff/foo
4067 @item 
4068 Invoke @code{/bin/rm ./file1 ./file2 ./file3}
4069 @item
4070 Change directory to /var/tmp/stuff/bar
4071 @item 
4072 Invoke @code{/bin/rm ./file99 ./file100 ./file101}
4073 @end enumerate
4075 This is a much more secure method.  We are no longer exposed to a race
4076 condition.  For many typical uses of @code{find}, this is the best
4077 strategy.   It's reasonably efficient, but the length of the command
4078 line is limited not just by the operating system limits, but also by
4079 how many files we actually need to delete from each directory.
4081 Is it possible to do any better?   In the case of general file
4082 processing, no.  However, in the specific case of deleting files it is
4083 indeed possible to do better.  
4085 @subsection Using the -delete action
4087 The most efficient and secure method of solving this problem is to use
4088 the @samp{-delete} action:
4090 @smallexample
4091 find /var/tmp/stuff -mtime +90 -delete
4092 @end smallexample
4094 This alternative is more efficient than any of the @samp{-exec} or
4095 @samp{-execdir} actions, since it entirely avoids the overhead of
4096 forking a new process and using @code{exec} to run @code{/bin/rm}.  It
4097 is also normally more efficient than @code{xargs} for the same
4098 reason.   The file deletion is performed from the directory containing
4099 the entry to be deleted, so the @samp{-delete} action has the same
4100 security advantages as the @samp{-execdir} action has.  
4102 The @samp{-delete} action was introduced by the BSD family of
4103 operating systems.
4105 @subsection Improving things still further
4107 Is it possible to improve things still further?  Not without either
4108 modifying the system library to the operating system or having more specific
4109 knowledge of the layout of the filesystem and disk I/O subsystem, or
4110 both.
4112 The @code{find} command traverses the filesystem, reading
4113 directories.  It then issues a separate system call for each file to
4114 be deleted.  If we could modify the operating system, there are
4115 potential gains that could be made:
4117 @itemize
4118 @item
4119 We could have a system call to which we pass more than one filename
4120 for deletion
4121 @item
4122 Alternatively, we could pass in a list of inode numbers (on GNU/Linux
4123 systems, @code{readdir()} also returns the inode number of each
4124 directory entry) to be deleted.
4125 @end itemize
4127 The above possibilities sound interesting, but from the kernel's point
4128 of view it is difficult to enforce standard Unix access controls for
4129 such processing by inode number.  Such a facility would probably
4130 need to be restricted to the superuser.
4132 Another way of improving performance would be to increase the
4133 parallelism of the process.  For example if the directory hierarchy we
4134 are searching is actually spread across a number of disks, we might
4135 somehow be able to arrange for @code{find} to process each disk in
4136 parallel.  In practice GNU @code{find} doesn't have such an intimate
4137 understanding of the system's filesystem layout and disk I/O
4138 subsystem.
4140 However, since the system administrator can have such an understanding
4141 they can take advantage of it like so:
4143 @smallexample
4144 find /var/tmp/stuff1 -mtime +90 -delete &
4145 find /var/tmp/stuff2 -mtime +90 -delete &
4146 find /var/tmp/stuff3 -mtime +90 -delete &
4147 find /var/tmp/stuff4 -mtime +90 -delete &
4148 wait
4149 @end smallexample
4151 In the example above, four separate instances of @code{find} are used
4152 to search four subdirectories in parallel.  The @code{wait} command
4153 simply waits for all of these to complete.  Whether this approach is
4154 more or less efficient than a single instance of @code{find} depends
4155 on a number of things:
4157 @itemize
4158 @item
4159 Are the directories being searched in parallel actually on separate
4160 disks?  If not, this parallel search might just result in a lot of
4161 disk head movement and so the speed might even be slower.
4162 @item
4163 Other activity - are other programs also doing things on those disks?
4164 @end itemize
4167 @subsection Conclusion
4169 The fastest and most secure way to delete files with the help of
4170 @code{find} is to use @samp{-delete}.  Using @code{xargs -0 -P N} can
4171 also make effective use of the disk, but it is not as secure.
4173 In the case where we're doing things other than deleting files, the
4174 most secure alternative is @samp{-execdir @dots{} +}, but this is not as
4175 portable as the insecure action @samp{-exec @dots{} +}.
4177 The @samp{-delete} action is not completely portable, but the only
4178 other possibility which is as secure (@samp{-execdir}) is no more
4179 portable.  The most efficient portable alternative is @samp{-exec
4180 @dots{}+}, but this is insecure and isn't supported by versions of GNU
4181 findutils prior to 4.2.12.
4183 @node Copying A Subset of Files
4184 @section Copying A Subset of Files
4186 Suppose you want to copy some files from @file{/source-dir} to
4187 @file{/dest-dir}, but there are a small number of files in
4188 @file{/source-dir} you don't want to copy. 
4190 One option of course is @code{cp /source-dir /dest-dir} followed by
4191 deletion of the unwanted material under @file{/dest-dir}.  But often
4192 that can be inconvenient, because for example we would have copied a
4193 large amount of extraneous material, or because @file{/dest-dir} is
4194 too small.  Naturally there are many other possible reasons why this
4195 strategy may be unsuitable.
4197 So we need to have some way of identifying which files we want to
4198 copy, and we need to have a way of copying that file list.  The second
4199 part of this condition is met by @code{cpio -p}.  Of course, we can
4200 identify the files we wish to copy by using @code{find}.  Here is a
4201 command that solves our problem:
4203 @example
4204 cd /source-dir
4205 find . -name '.snapshot' -prune -o \( \! -name '*~' -print0 \) | 
4206 cpio -pmd0   /dest-dir
4207 @end example
4209 The first part of the @code{find} command here identifies files or
4210 directoires named @file{.snapshot} and tells @code{find} not to
4211 recurse into them (since they do not need to be copied).  The
4212 combination @code{-name '.snapshot' -prune} yields false for anything
4213 that didn't get pruned, but it is exactly those files we want to
4214 copy.  Therefore we need to use an OR (@samp{-o}) condition to
4215 introduce the rest of our expression.  The remainder of the expression
4216 simply arranges for the name of any file not ending in @samp{~} to be
4217 printed.  
4219 Using @code{-print0} ensures that white space characters in file names
4220 do not pose a problem.  The @code{cpio} command does the actual work
4221 of copying files.  The program as a whole fails if the @code{cpio}
4222 program returns nonzero.  If the @code{find} command returns non-zero
4223 on the other hand, the Unix shell will not diagnose a problem (since
4224 @code{find} is not the last command in the pipeline).
4227 @node Updating A Timestamp File
4228 @section Updating A Timestamp File
4230 Suppose we have a directory full of files which is maintained with a
4231 set of automated tools; perhaps one set of tools updates them and
4232 another set of tools uses the result.  In this situation, it might be
4233 useful for the second set of tools to know if the files have recently
4234 been changed.  It might be useful, for example, to have a 'timestamp'
4235 file which gives the timestamp on the newest file in the collection.
4237 We can use @code{find} to achieve this, but there are several
4238 different ways to do it.
4240 @subsection Updating the Timestamp The Wrong Way
4242 The obvious but wrong answer is just to use @samp{-newer}:-
4244 @smallexample
4245 find subdir -newer timestamp -exec touch -r @{@} timestamp \; 
4246 @end smallexample
4248 This does the right sort of thing but has a bug.  Suppose that two
4249 files in the subdirectory have been updated, and that these are called
4250 @file{file1} and @file{file2}.  The command above will update
4251 @file{timestamp} with the modification time of @file{file1} or that of
4252 @file{file2}, but we don't know which one.  Since the timestamps on
4253 @file{file1} and @file{file2} will in general be different, this could
4254 well be the wrong value.
4256 One solution to this problem is to modify @code{find} to recheck the
4257 modification time of @file{timestamp} every time a file is to be
4258 compared against it, but that will reduce the performance of
4259 @code{find}.
4261 @subsection Using the test utility to compare timestamps
4263 The @code{test} command can be used to compare timestamps:
4265 @smallexample
4266 find subdir -exec test @{@} -nt timestamp \; -exec touch -r @{@} timestamp \; 
4267 @end smallexample
4269 This will ensure that any changes made to the modification time of
4270 @file{timestamp} that take place during the execution of @code{find}
4271 are taken into account.  This resolves our earlier problem, but
4272 unfortunately this runs much more slowly.
4274 @subsection A combined approach
4276 We can of course still use @samp{-newer} to cut down on the number of
4277 calls to @code{test}:
4279 @smallexample
4280 find subdir -newer timestamp -a \
4281      -exec test @{@} -nt timestamp \; -a \
4282      -exec touch -r @{@} timestamp \; 
4283 @end smallexample
4285 Here, the @samp{-newer} test excludes all the files which are
4286 definitely older than the timestamp, but all the files which are newer
4287 than the old value of the timestamp are compared against the current
4288 updated timestamp.
4290 This is indeed faster in general, but the speed difference will depend
4291 on how many updated files there are.
4293 @subsection Using -printf and sort to compare timestamps
4295 It is possible to use the @samp{-printf} action to abandon the use of
4296 @code{test} entirely:
4298 @smallexample
4299 newest=$(find subdir -newer timestamp -printf "%A@:%p\n" | 
4300            sort -n | 
4301            tail -1 | 
4302            cut -d: -f2- ) 
4303 touch -r "$@{newest:-timestamp@}" timestamp
4304 @end smallexample
4306 The command above works by generating a list of the timestamps and
4307 names of all the files which are newer than the timestamp.  The
4308 @code{sort}, @code{tail} and @code{cut} commands simply pull out the
4309 name of the file with the largest timestamp value (that is, the latest
4310 file).  The @code{touch} command is then used to update the timestamp,
4312 The @code{"$@{newest:-timestamp@}"} expression simply expands to the
4313 value of @code{$newest} if that variable is set, but to
4314 @file{timestamp} otherwise.  This ensures that an argument is always
4315 given to the @samp{-r} option of the @code{touch} command.
4317 This approach seems quite efficient, but unfortunately it has a
4318 problem.  Many operating systems now keep file modification time
4319 information at a granularity which is finer than one second.
4320 Findutils version 4.3.3 and later will print a fractional part with
4321 %A@@, but older versions will not.
4324 @subsection Solving the problem with make
4326 Another tool which often works with timestamps is @code{make}.  We can
4327 use @code{find} to generate a @file{Makefile} file on the fly and then
4328 use @code{make} to update the timestamps:
4330 @smallexample
4331 makefile=$(mktemp)
4332 find subdir \
4333         \( \! -xtype l \) \
4334         -newer timestamp \
4335         -printf "timestamp:: %p\n\ttouch -r %p timestamp\n\n" > "$makefile"
4336 make -f "$makefile"
4337 rm   -f "$makefile"
4338 @end smallexample
4340 Unfortunately although the solution above is quite elegant, it fails
4341 to cope with white space within file names, and adjusting it to do so
4342 would require a rather complex shell script.
4345 @subsection Coping with odd filenames too
4347 We can fix both of these problems (looping and problems with white
4348 space), and do things more efficiently too.  The following command
4349 works with newlines and doesn't need to sort the list of filenames.
4351 @smallexample
4352 find subdir -newer timestamp -printf "%A@@:%p\0" | 
4353    perl -0 newest.pl |
4354    xargs --no-run-if-empty --null -i \
4355       find @{@} -maxdepth 0 -newer timestamp -exec touch -r @{@} timestamp \;
4356 @end smallexample
4358 The first @code{find} command generates a list of files which are
4359 newer than the original timestamp file, and prints a list of them with
4360 their timestamps.  The @file{newest.pl} script simply filters out all
4361 the filenames which have timestamps which are older than whatever the
4362 newest file is:-
4364 @smallexample
4365 @verbatim
4366 #! /usr/bin/perl -0
4367 my @newest = ();
4368 my $latest_stamp = undef;
4369 while (<>) {
4370     my ($stamp, $name) = split(/:/);
4371     if (!defined($latest_stamp) || ($tstamp > $latest_stamp)) {
4372         $latest_stamp = $stamp;
4373         @newest = ();
4374     }
4375     if ($tstamp >= $latest_stamp) {
4376         push @newest, $name;
4377     }
4379 print join("\0", @newest);
4380 @end verbatim
4381 @end smallexample
4383 This prints a list of zero or more files, all of which are newer than
4384 the original timestamp file, and which have the same timestamp as each
4385 other, to the nearest second.  The second @code{find} command takes
4386 each resulting file one at a time, and if that is newer than the
4387 timestamp file, the timestamp is updated.
4389 @node Security Considerations
4390 @chapter Security Considerations
4392 Security considerations are important if you are using @code{find} or
4393 @code{xargs} to search for or process files that don't belong to you
4394 or which other people have control.  Security considerations
4395 relating to @code{locate} may also apply if you have files which you
4396 do not want others to see.
4398 The most severe forms of security problems affecting
4399 @code{find} and related programs are when third parties bring
4400 about a situation allowing them to do something
4401 they would normally not be able to accomplish.  This is called @emph{privilege
4402 elevation}.  This might include deleting files they would not normally
4403 be able to delete.  It is common for the operating system to periodically
4404 invoke @code{find} for self-maintenance purposes.  These invocations of
4405 @code{find} are particularly problematic from a security point of view
4406 as these are often invoked by the superuser and search the entire
4407 filesystem hierarchy.  Generally, the severity of any associated problem depends
4408 on what the system is going to do with the files found by @code{find}.
4410 @menu
4411 * Levels of Risk::      What is your level of exposure to security problems?
4412 * Security Considerations for find::  Security problems with find
4413 * Security Considerations for xargs:: Security problems with xargs
4414 * Security Considerations for locate:: Security problems with locate
4415 * Security Summary:: That was all very complex, what does it boil down to?
4416 @end menu
4419 @node Levels of Risk
4420 @section Levels of Risk
4422 There are some security risks inherent in the use of @code{find},
4423 @code{xargs} and (to a lesser extent) @code{locate}.  The severity of
4424 these risks depends on what sort of system you are using:
4426 @table @strong
4427 @item High risk
4428 Multi-user systems where you do not control (or trust) the other
4429 users, and on which you execute @code{find}, including areas where
4430 those other users can manipulate the filesystem (for example beneath
4431 @file{/home} or @file{/tmp}).
4433 @item Medium Risk
4434 Systems where the actions of other users can create file names chosen
4435 by them, but to which they don't have access while @code{find} is
4436 being run.  This access might include leaving programs running (shell
4437 background jobs, @code{at} or @code{cron} tasks, for example).  On
4438 these sorts of systems, carefully written commands (avoiding use of
4439 @samp{-print} for example) should not expose you to a high degree of
4440 risk.  Most systems fall into this category.
4442 @item Low Risk
4443 Systems to which untrusted parties do not have access, cannot create
4444 file names of their own choice (even remotely) and which contain no
4445 security flaws which might enable an untrusted third party to gain
4446 access.  Most systems do not fall into this category because there are
4447 many ways in which external parties can affect the names of files that
4448 are created on your system.  The system on which I am writing this for
4449 example automatically downloads software updates from the Internet;
4450 the names of the files in which these updates exist are chosen by
4451 third parties@footnote{Of course, I trust these parties to a large
4452 extent anyway, because I install software provided by them; I choose
4453 to trust them in this way, and that's a deliberate choice}.
4454 @end table
4456 In the discussion above, ``risk'' denotes the likelihood that someone
4457 can cause @code{find}, @code{xargs}, @code{locate} or some other
4458 program which is controlled by them to do something you did not
4459 intend.  The levels of risk suggested do not take any account of the
4460 consequences of this sort of event.  That is, if you operate a ``low
4461 risk'' type system, but the consequences of a security problem are
4462 disastrous, then you should still give serious thought to all the
4463 possible security problems, many of which of course will not be
4464 discussed here -- this section of the manual is intended to be
4465 informative but not comprehensive or exhaustive.
4467 If you are responsible for the operation of a system where the
4468 consequences of a security problem could be very important, you should
4469 do two things:-
4471 @enumerate
4472 @item Define a security policy which defines who is allowed to do what
4473 on your system.
4474 @item Seek competent advice on how to enforce your policy, detect
4475 breaches of that policy, and take account of any potential problems
4476 that might fall outside the scope of your policy.
4477 @end enumerate
4480 @node Security Considerations for find
4481 @section Security Considerations for @code{find}
4484 Some of the actions @code{find} might take have a direct effect;
4485 these include @code{-exec} and @code{-delete}.  However, it is also
4486 common to use @code{-print} explicitly or implicitly, and so if
4487 @code{find} produces the wrong list of file names, that can also be a
4488 security problem; consider the case for example where @code{find} is
4489 producing a list of files to be deleted.
4491 We normally assume that the @code{find} command line expresses the
4492 file selection criteria and actions that the user had in mind -- that
4493 is, the command line is ``trusted'' data.
4495 From a security analysis point of view, the output of @code{find}
4496 should be correct; that is, the output should contain only the names
4497 of those files which meet the user's criteria specified on the command
4498 line.  This applies for the @code{-exec} and @code{-delete} actions;
4499 one can consider these to be part of the output.
4501 On the other hand, the contents of the filesystem can be manipulated
4502 by other people, and hence we regard this as ``untrusted'' data.  This
4503 implies that the @code{find} command line is a filter which converts
4504 the untrusted contents of the filesystem into a correct list of output
4505 files.
4507 The filesystem will in general change while @code{find} is searching
4508 it; in fact, most of the potential security problems with @code{find}
4509 relate to this issue in some way.
4511 @dfn{Race conditions} are a general class of security problem where the
4512 relative ordering of actions taken by @code{find} (for example) and
4513 something else are critically important in getting the correct and expected result@footnote{This is more or less the
4514 definition of the term ``race condition''} .
4516 For @code{find}, an attacker might move or rename files or directories in
4517 the hope that an action might be taken against a file which was not
4518 normally intended to be affected.  Alternatively, this sort of attack
4519 might be intended to persuade @code{find} to search part of the
4520 filesystem which would not normally be included in the search
4521 (defeating the @code{-prune} action for example).
4523 @menu
4524 * Problems with -exec and filenames::
4525 * Changing the Current Working Directory::
4526 * Race Conditions with -exec::
4527 * Race Conditions with -print and -print0::
4528 @end menu
4530 @node Problems with -exec and filenames
4531 @subsection Problems with -exec and filenames
4533 It is safe in many cases to use the @samp{-execdir} action with any
4534 file name.  Because @samp{-execdir} prefixes the arguments it passes
4535 to programs with @samp{./}, you will not accidentally pass an argument
4536 which is interpreted as an option.  For example the file @file{-f}
4537 would be passed to @code{rm} as @file{./-f}, which is harmless.
4539 However, your degree of safety does depend on the nature of the
4540 program you are running.  For example constructs such as these two commands
4542 @example
4543 # risky
4544 find -exec sh -c "something @{@}" \;
4545 find -execdir sh -c "something @{@}" \;
4546 @end example
4548 are very dangerous.  The reason for this is that the @samp{@{@}} is
4549 expanded to a filename which might contain a semicolon or other
4550 characters special to the shell.  If for example someone creates the
4551 file @file{/tmp/foo; rm -rf $HOME} then the two commands above could
4552 delete someone's home directory.
4554 So for this reason do not run any command which will pass untrusted
4555 data (such as the names of files) to commands which interpret
4556 arguments as commands to be further interpreted (for example
4557 @samp{sh}).
4559 In the case of the shell, there is a clever workaround for this
4560 problem:
4562 @example
4563 # safer 
4564 find -exec sh -c 'something "$@@"' @{@} \;
4565 find -execdir sh -c 'something "$@@"' @{@}\;
4566 @end example
4568 This approach is not guaranteed to avoid every problem, but it is much
4569 safer than substituting data of an attacker's choice into the text of
4570 a shell command.
4572 @node Changing the Current Working Directory
4573 @subsection Changing the Current Working Directory
4575 As @code{find} searches the filesystem, it finds subdirectories and
4576 then searches within them by changing its working directory.  First,
4577 @code{find} reaches and recognises a subdirectory.  It then decides if that
4578 subdirectory meets the criteria for being searched; that is, any
4579 @samp{-xdev} or @samp{-prune} expressions are taken into account.  The
4580 @code{find} program will then change working directory and proceed to
4581 search the directory.
4583 A race condition attack might take the form that once the checks
4584 relevant to @samp{-xdev} and @samp{-prune} have been done, an attacker
4585 might rename the directory that was being considered, and put in its
4586 place a symbolic link that actually points somewhere else.
4588 The idea behind this attack is to fool @code{find} into going into the
4589 wrong directory.  This would leave @code{find} with a working
4590 directory chosen by an attacker, bypassing any protection apparently
4591 provided by @samp{-xdev} and @samp{-prune}, and any protection
4592 provided by being able to @emph{not} list particular directories on
4593 the @code{find} command line.  This form of attack is particularly
4594 problematic if the attacker can predict when the @code{find} command
4595 will be run, as is the case with @code{cron} tasks for example.
4597 GNU @code{find} has specific safeguards to prevent this general class
4598 of problem.  The exact form of these safeguards depends on the
4599 properties of your system.
4601 @menu
4602 * O_NOFOLLOW::                     Safely changing directory using fchdir().
4603 * Systems without O_NOFOLLOW::     Checking for symbolic links after chdir().
4604 @end menu
4606 @node O_NOFOLLOW
4607 @subsubsection O_NOFOLLOW
4609 If your system supports the O_NOFOLLOW flag @footnote{GNU/Linux
4610 (kernel version 2.1.126 and later) and FreeBSD (3.0-CURRENT and later)
4611 support this} to the @code{open(2)} system call, @code{find} uses it
4612 when safely changing directory.  The target directory is first opened
4613 and then @code{find} changes working directory with the
4614 @code{fchdir()} system call.  This ensures that symbolic links are not
4615 followed, preventing the sort of race condition attack in which use
4616 is made of symbolic links.
4618 If for any reason this approach does not work, @code{find} will fall
4619 back on the method which is normally used if O_NOFOLLOW is not
4620 supported.
4622 You can tell if your system supports O_NOFOLLOW by running
4624 @example
4625 find --version
4626 @end example
4628 This will tell you the version number and which features are enabled.
4629 For example, if I run this on my system now, this gives:
4630 @example
4631 GNU find version 4.2.18-CVS
4632 Features enabled: D_TYPE O_NOFOLLOW(enabled)
4633 @end example
4635 Here, you can see that I am running a version of @code{find} which was
4636 built from the development (CVS) code prior to the release of
4637 findutils-4.2.18, and that the D_TYPE and O_NOFOLLOW features are
4638 present.  O_NOFOLLOW is qualified with ``enabled''.  This simply means
4639 that the current system seems to support O_NOFOLLOW.  This check is
4640 needed because it is possible to build @code{find} on a system that
4641 defines O_NOFOLLOW and then run it on a system that ignores the
4642 O_NOFOLLOW flag.  We try to detect such cases at startup by checking
4643 the operating system and version number; when this happens you will
4644 see ``O_NOFOLLOW(disabled)'' instead.
4646 @node Systems without O_NOFOLLOW
4647 @subsubsection Systems without O_NOFOLLOW
4649 The strategy for preventing this type of problem on systems that lack
4650 support for the O_NOFOLLOW flag is more complex.  Each time
4651 @code{find} changes directory, it examines the directory it is about
4652 to move to, issues the @code{chdir()} system call, and then checks
4653 that it has ended up in the subdirectory it expected.  If all is as
4654 expected, processing continues as normal.  However, there are two main
4655 reasons why the directory might change: the use of an automounter and
4656 the someone removing the old directory and replacing it with something
4657 else while @code{find} is trying to descend into it.
4659 Where a filesystem ``automounter'' is in use it can be the case that
4660 the use of the @code{chdir()} system call can itself cause a new
4661 filesystem to be mounted at that point.  On systems that do not
4662 support O_NOFOLLOW, this will cause @code{find}'s security check to
4663 fail.
4665 However, this does not normally represent a security problem, since
4666 the automounter configuration is normally set up by the system
4667 administrator.  Therefore, if the @code{chdir()} sanity check fails,
4668 @code{find} will make one more attempt@footnote{This may not be the
4669 case for the fts-based executable}.  If that succeeds, execution
4670 carries on as normal.  This is the usual case for automounters.
4672 Where an attacker is trying to exploit a race condition, the problem
4673 may not have gone away on the second attempt.  If this is the case,
4674 @code{find} will issue a warning message and then ignore that
4675 subdirectory.  When this happens, actions such as @samp{-exec} or
4676 @samp{-print} may already have taken place for the problematic
4677 subdirectory.  This is because @code{find} applies tests and actions
4678 to directories before searching within them (unless @samp{-depth} was
4679 specified).
4681 Because of the nature of the directory-change operation and security
4682 check, in the worst case the only things that @code{find} would have
4683 done with the directory are to move into it and back out to the
4684 original parent.  No operations would have been performed within that
4685 directory.
4687 @node Race Conditions with -exec
4688 @subsection Race Conditions with -exec
4690 The @samp{-exec} action causes another program to be run.  It passes
4691 to the program the name of the file which is being considered at the
4692 time.  The invoked program will typically then perform some action
4693 on that file.  Once again, there is a race condition which can be
4694 exploited here.  We shall take as a specific example the command
4696 @example
4697 find /tmp -path /tmp/umsp/passwd -exec /bin/rm
4698 @end example
4700 In this simple example, we are identifying just one file to be deleted
4701 and invoking @code{/bin/rm} to delete it.  A problem exists because
4702 there is a time gap between the point where @code{find} decides that
4703 it needs to process the @samp{-exec} action and the point where the
4704 @code{/bin/rm} command actually issues the @code{unlink()} system
4705 call to delete the file from the filesystem.  Within this time period, an attacker can rename the
4706 @file{/tmp/umsp} directory, replacing it with a symbolic link to
4707 @file{/etc}.  There is no way for @code{/bin/rm} to determine that it
4708 is working on the same file that @code{find} had in mind.  Once the
4709 symbolic link is in place, the attacker has persuaded @code{find} to
4710 cause the deletion of the @file{/etc/passwd} file, which is not the
4711 effect intended by the command which was actually invoked.
4713 One possible defence against this type of attack is to modify the
4714 behaviour of @samp{-exec} so that the @code{/bin/rm} command is run
4715 with the argument @file{./passwd} and a suitable choice of working
4716 directory.  This would allow the normal sanity check that @code{find}
4717 performs to protect against this form of attack too.  Unfortunately,
4718 this strategy cannot be used as the POSIX standard specifies that the
4719 current working directory for commands invoked with @samp{-exec} must
4720 be the same as the current working directory from which @code{find}
4721 was invoked.  This means that the @samp{-exec} action is inherently
4722 insecure and can't be fixed.
4724 GNU @code{find} implements a more secure variant of the @samp{-exec}
4725 action, @samp{-execdir}.  The @samp{-execdir} action
4726 ensures that it is not necessary to dereference subdirectories to
4727 process target files.  The current directory used to invoke programs
4728 is the same as the directory in which the file to be processed exists
4729 (@file{/tmp/umsp} in our example, and only the basename of the file to
4730 be processed is passed to the invoked command, with a @samp{./}
4731 prepended (giving @file{./passwd} in our example).
4733 The @samp{-execdir} action refuses to do anything if the current
4734 directory is included in the @var{$PATH} environment variable.  This
4735 is necessary because @samp{-execdir} runs programs in the same
4736 directory in which it finds files -- in general, such a directory
4737 might be writable by untrusted users.  For similar reasons,
4738 @samp{-execdir} does not allow @samp{@{@}} to appear in the name of
4739 the command to be run.
4741 @node Race Conditions with -print and -print0
4742 @subsection Race Conditions with -print and -print0
4744 The @samp{-print} and @samp{-print0} actions can be used to produce a
4745 list of files matching some criteria, which can then be used with some
4746 other command, perhaps with @code{xargs}.  Unfortunately, this means
4747 that there is an unavoidable time gap between @code{find} deciding
4748 that one or more files meet its criteria and the relevant command
4749 being executed.  For this reason, the @samp{-print} and @samp{-print0}
4750 actions are just as insecure as @samp{-exec}.
4752 In fact, since the construction
4754 @example
4755 find @dots{}  -print | xargs @enddots{}
4756 @end example
4758 does not cope correctly with newlines or other ``white space'' in
4759 file names, and copes poorly with file names containing quotes, the
4760 @samp{-print} action is less secure even than @samp{-print0}.
4763 @comment  node-name,  next,  previous,  up
4764 @comment @node Security Considerations for xargs
4765 @node Security Considerations for xargs
4766 @section Security Considerations for @code{xargs}
4768 The description of the race conditions affecting the @samp{-print}
4769 action of @code{find} shows that @code{xargs} cannot be secure if it
4770 is possible for an attacker to modify a filesystem after @code{find}
4771 has started but before @code{xargs} has completed all its actions.
4773 However, there are other security issues that exist even if it is not
4774 possible for an attacker to have access to the filesystem in real
4775 time.  Firstly, if it is possible for an attacker to create files with
4776 names of their choice on the filesystem, then @code{xargs} is
4777 insecure unless the @samp{-0} option is used.  If a file with the name
4778 @file{/home/someuser/foo/bar\n/etc/passwd} exists (assume that
4779 @samp{\n} stands for a newline character), then @code{find @dots{} -print}
4780 can be persuaded to print three separate lines:
4782 @example
4783 /home/someuser/foo/bar
4785 /etc/passwd
4786 @end example
4788 If it finds a blank line in the input, @code{xargs} will ignore it.
4789 Therefore, if some action is to be taken on the basis of this list of
4790 files, the @file{/etc/passwd} file would be included even if this was
4791 not the intent of the person running find.  There are circumstances in
4792 which an attacker can use this to their advantage.  The same
4793 consideration applies to file names containing ordinary spaces rather
4794 than newlines, except that of course the list of file names will no
4795 longer contain an ``extra'' newline.
4797 This problem is an unavoidable consequence of the default behaviour of
4798 the @code{xargs} command, which is specified by the POSIX standard.
4799 The only ways to avoid this problem are either to avoid all use of
4800 @code{xargs} in favour for example of @samp{find -exec} or (where
4801 available) @samp{find -execdir}, or to use the @samp{-0} option, which
4802 ensures that @code{xargs} considers file names to be separated by
4803 ASCII NUL characters rather than whitespace.  However, useful as this
4804 option is, the POSIX standard does not make it mandatory.
4806 POSIX also specifies that @code{xargs} interprets quoting and trailing
4807 whitespace specially in filenames, too.  This means that using
4808 @code{find ... -print | xargs ...} can cause the commands run by
4809 @code{xargs} to receive a list of file names which is not the same as
4810 the list printed by @code{find}.   The interpretation of quotes and
4811 trailing whitespace is turned off by the @samp{-0} argument to
4812 @code{xargs}, which is another reason to use that option.
4814 @comment  node-name,  next,  previous,  up
4815 @node Security Considerations for locate
4816 @section Security Considerations for @code{locate}
4818 @subsection Race Conditions
4819 It is fairly unusual for the output of @code{locate} to be fed into
4820 another command.  However, if this were to be done, this would raise
4821 the same set of security issues as the use of @samp{find @dots{} -print}.
4822 Although the problems relating to whitespace in file names can be
4823 resolved by using @code{locate}'s @samp{-0} option, this still leaves
4824 the race condition problems associated with @samp{find @dots{} -print0}.
4825 There is no way to avoid these problems in the case of @code{locate}.
4827 @subsection Long File Name Bugs with Old-Format Databases
4828 Old versions of @code{locate} have a bug in the way that old-format
4829 databases are read.  This bug affects the following versions of
4830 @code{locate}:
4832 @enumerate
4833 @item All releases prior to 4.2.31
4834 @item All 4.3.x releases prior to 4.3.7
4835 @end enumerate
4837 The affected versions of @code{locate} read file names into a
4838 fixed-length 1026 byte buffer, allocated on the heap.  This buffer is
4839 not extended if file names are too long to fit into the buffer.  No
4840 range checking on the length of the filename is performed.  This could
4841 in theory lead to a privilege escalation attack.  Findutils versions
4842 4.3.0 to 4.3.6 are also affected.
4844 On systems using the old database format and affected versions of
4845 @code{locate}, carefully-chosen long file names could in theory allow
4846 malicious users to run code of their choice as any user invoking
4847 locate.
4849 If remote users can choose the names of files stored on your system,
4850 and these files are indexed by @code{updatedb}, this may be a remote
4851 security vulnerability.  Findutils version 4.2.31 and findutils
4852 version 4.3.7 include fixes for this problem.  The @code{updatedb},
4853 @code{bigram} and @code{code} programs do no appear to be affected.
4855 If you are also using GNU coreutils, you can use the following command
4856 to determine the length of the longest file name on a given system:
4858 @example
4859 find / -print0 | tr -c '\0' 'x' | tr '\0' '\n' | wc -L
4860 @end example
4862 Although this problem is significant, the old database format is not
4863 the default, and use of the old database format is not common.  Most
4864 installations and most users will not be affected by this problem.  
4868 @node Security Summary
4869 @section Summary
4871 Where untrusted parties can create files on the system, or affect the
4872 names of files that are created, all uses for @code{find},
4873 @code{locate} and @code{xargs} have known security problems except the
4874 following:
4876 @table @asis
4877 @item Informational use only
4878 Uses where the programs are used to prepare lists of file names upon
4879 which no further action will ever be taken.
4881 @item @samp{-delete}
4882 Use of the @samp{-delete} action with @code{find} to delete files
4883 which meet specified criteria
4885 @item @samp{-execdir}
4886 Use of the @samp{-execdir} action with @code{find} where the
4887 @env{PATH} environment variable contains directories which contain
4888 only trusted programs.
4889 @end table
4891 @comment  node-name,  next,  previous,  up
4892 @node Error Messages
4893 @chapter Error Messages
4895 This section describes some of the error messages sometimes made by
4896 @code{find}, @code{xargs}, or @code{locate}, explains them and in some
4897 cases provides advice as to what you should do about this.
4899 This manual is written in English.  The GNU findutils software
4900 features translations of error messages for many languages.  For this
4901 reason the error messages produced by the programs are made to be as
4902 self-explanatory as possible.  This approach avoids leaving people to
4903 figure out which test an English-language error message corresponds
4904 to.  Error messages which are self-explanatory will not normally be
4905 mentioned in this document.  For those messages mentioned in this
4906 document, only the English-language version of the message will be
4907 listed.
4909 @menu
4910 * Error Messages From find::
4911 * Error Messages From xargs::
4912 * Error Messages From locate::
4913 * Error Messages From updatedb::
4914 @end menu
4916 @node Error Messages From find
4917 @section Error Messages From @code{find}
4919 Most error messages produced by find are self-explanatory.  Error
4920 messages sometimes include a filename.  When this happens, the
4921 filename is quoted in order to prevent any unusual characters in the
4922 filename making unwanted changes in the state of the terminal.
4924 @table @samp
4925 @item invalid predicate `-foo'
4926 This means that the @code{find} command line included something that
4927 started with a dash or other special character.  The @code{find}
4928 program tried to interpret this as a test, action or option, but
4929 didn't recognise it.  If it was intended to be a test, check what was
4930 specified against the documentation.  If, on the other hand, the
4931 string is the name of a file which has been expanded from a wildcard
4932 (for example because you have a @samp{*} on the command line),
4933 consider using @samp{./*} or just @samp{.} instead.
4935 @item unexpected extra predicate
4936 This usually happens if you have an extra bracket on the command line
4937 (for example @samp{find . -print \)}).
4939 @item Warning: filesystem /path/foo has recently been mounted
4940 @itemx Warning: filesystem /path/foo has recently been unmounted
4941 These messages might appear when @code{find} moves into a directory
4942 and finds that the device number and inode are different to what it
4943 expected them to be.  If the directory @code{find} has moved into is
4944 on an network filesystem (NFS), it will not issue this message, because
4945 @code{automount} frequently mounts new filesystems on directories as
4946 you move into them (that is how it knows you want to use the
4947 filesystem).  So, if you do see this message, be wary ---
4948 @code{automount} may not have been responsible.  Consider the
4949 possibility that someone else is manipulating the filesystem while
4950 @code{find} is running.  Some people might do this in order to mislead
4951 @code{find} or persuade it to look at one set of files when it thought
4952 it was looking at another set.
4954 @item /path/foo changed during execution of find (old device number 12345, new device number 6789, filesystem type is <whatever>) [ref XXX]
4955 This message is issued when @code{find} moves into a directory and ends up
4956 somewhere it didn't expect to be.  This happens in one of two
4957 circumstances.  Firstly, this happens when @code{automount} intervenes
4958 on a system where @code{find} doesn't know how to determine what
4959 the current set of mounted filesystems is.
4961 Secondly, this can happen when the device number of a directory
4962 appears to change during a change of current directory, but
4963 @code{find} is moving up the filesystem hierarchy rather than down into it.
4964 In order to prevent @code{find} wandering off into some unexpected
4965 part of the filesystem, we stop it at this point.
4967 @item Don't know how to use getmntent() to read `/etc/mtab'.  This is a bug.
4968 This message is issued when a problem similar to the above occurs on a
4969 system where @code{find} doesn't know how to figure out the current
4970 list of mount points.  Ask for help on @email{bug-findutils@@gnu.org}.
4972 @item /path/foo/bar changed during execution of find (old inode number 12345, new inode number 67893, filesystem type is <whatever>) [ref XXX]"),
4973 This message is issued when @code{find} moves into a directory and
4974 discovers that the inode number of that directory
4975 is different from the inode number that it obtained when it examined the
4976 directory previously.  This usually means that while
4977 @code{find} was deep in a directory hierarchy doing a
4978 time consuming operation, somebody has moved one of the parent directories to
4979 another location in the same filesystem.  This may or may not have been done
4980 maliciously.  In any case, @code{find} stops at this point
4981 to avoid traversing parts of the filesystem that it wasn't
4982 intended.  You can use @code{ls -li} or @code{find /path -inum
4983 12345 -o -inum 67893} to find out more about what has happened.
4985 @item sanity check of the fnmatch() library function failed.
4986 Please submit a bug report.  You may well be asked questions about
4987 your system, and if you compiled the @code{findutils} code yourself,
4988 you should keep your copy of the build tree around.  The likely
4989 explanation is that your system has a buggy implementation of
4990 @code{fnmatch} that looks enough like the GNU version to fool
4991 @code{configure}, but which doesn't work properly.
4993 @item cannot fork
4994 This normally happens if you use the @code{-exec} action or
4995 something similar (@code{-ok} and so forth) but the system has run out
4996 of free process slots.  This is either because the system is very busy
4997 and the system has reached its maximum process limit, or because you
4998 have a resource limit in place and you've reached it.  Check the
4999 system for runaway processes (with @code{ps}, if possible).  Some process
5000 slots are normally reserved for use by @samp{root}.
5002 @item some-program terminated by signal 99
5003 Some program which was launched with @code{-exec} or similar was killed
5004 with a fatal signal.  This is just an advisory message.
5005 @end table
5008 @node Error Messages From xargs
5009 @section Error Messages From xargs
5011 @table @samp
5012 @item environment is too large for exec
5013 This message means that you have so many environment variables set (or
5014 such large values for them) that there is no room within the
5015 system-imposed limits on program command line argument length to
5016 invoke any program.  This is an unlikely situation and is more likely
5017 result of an attempt to test the limits of @code{xargs}, or break it.
5018 Please try unsetting some environment variables, or exiting the
5019 current shell.  You can also use @samp{xargs --show-limits} to
5020 understand the relevant sizes.
5022 @item can not fit single argument within argument list size limit
5023 You are using the @samp{-I} option and @code{xargs} doesn't have
5024 enough space to build a command line because it has read a really
5025 large item and it doesn't fit.  You can probably work around this
5026 problem with the @samp{-s} option, but the default size is pretty
5027 large.  This is a rare situation and is more likely an attempt to test
5028 the limits of @code{xargs}, or break it.  Otherwise, you will need to
5029 try to shorten the problematic argument or not use @code{xargs}.
5031 @item cannot fork
5032 See the description of the similar message for @code{find}.
5034 @item <program>: exited with status 255; aborting
5035 When a command run by @code{xargs} exits with status 255, @code{xargs}
5036 is supposed to stop.  If this is not what you intended, wrap the
5037 program you are trying to invoke in a shell script which doesn't
5038 return status 255.
5040 @item <program>: terminated by signal 99
5041 See the description of the similar message for @code{find}.
5042 @end table
5044 @node Error Messages From locate
5045 @section Error Messages From @code{locate}
5047 @table @samp
5048 @item warning: database @file{@value{LOCATE_DB}} is more than 8 days old
5049 The @code{locate} program relies on a database which is periodically
5050 built by the @code{updatedb} program.  That hasn't happened in a long
5051 time.  To fix this problem, run @code{updatedb} manually.  This can
5052 often happen on systems that are generally not left on, so the
5053 periodic ``cron'' task which normally does this doesn't get a chance
5054 to run.
5056 @item locate database @file{@value{LOCATE_DB}} is corrupt or invalid
5057 This should not happen.  Re-run @code{updatedb}.  If that works, but
5058 @code{locate} still produces this error, run @code{locate --version}
5059 and @code{updatedb --version}.  These should produce the same output.
5060 If not, you are using a mixed toolset; check your @samp{$PATH}
5061 environment variable and your shell aliases (if you have any).  If
5062 both programs claim to be GNU versions, this is a bug; all versions of
5063 these programs should interoperate without problem.  Ask for help on
5064 @email{bug-findutils@@gnu.org}.
5065 @end table
5068 @node Error Messages From updatedb
5069 @section Error Messages From updatedb
5071 The @code{updatedb} program (and the programs it invokes) do issue
5072 error messages, but none seem to be candidates for guidance.  If
5073 you are having a problem understanding one of these, ask for help on
5074 @email{bug-findutils@@gnu.org}.
5077 @node Primary Index
5078 @unnumbered @code{find} Primary Index
5080 This is a list of all of the primaries (tests, actions, and options)
5081 that make up @code{find} expressions for selecting files.  @xref{find
5082 Expressions}, for more information on expressions.
5084 @printindex fn
5086 @bye
5088 @comment texi related words used by Emacs' spell checker ispell.el
5090 @comment LocalWords: texinfo setfilename settitle setchapternewpage
5091 @comment LocalWords: iftex finalout ifinfo DIR titlepage vskip pt
5092 @comment LocalWords: filll dir samp dfn noindent xref pxref
5093 @comment LocalWords: var deffn texi deffnx itemx emph asis
5094 @comment LocalWords: findex smallexample subsubsection cindex
5095 @comment LocalWords: dircategory direntry itemize
5097 @comment other words used by Emacs' spell checker ispell.el
5098 @comment LocalWords: README fred updatedb xargs Plett Rendell akefile
5099 @comment LocalWords: args grep Filesystems fo foo fOo wildcards iname
5100 @comment LocalWords: ipath regex iregex expr fubar regexps
5101 @comment LocalWords: metacharacters macs sr sc inode lname ilname
5102 @comment LocalWords: sysdep noleaf ls inum xdev filesystems usr atime
5103 @comment LocalWords: ctime mtime amin cmin mmin al daystart Sladkey rm
5104 @comment LocalWords: anewer cnewer bckw rf xtype uname gname uid gid
5105 @comment LocalWords: nouser nogroup chown chgrp perm ch maxdepth
5106 @comment LocalWords: mindepth cpio src CD AFS statted stat fstype ufs
5107 @comment LocalWords: nfs tmp mfs printf fprint dils rw djm Nov lwall
5108 @comment LocalWords: POSIXLY fls fprintf strftime locale's EDT GMT AP
5109 @comment LocalWords: EST diff perl backquotes sprintf Falstad Oct cron
5110 @comment LocalWords: eg vmunix mkdir afs allexec allwrite ARG bigram
5111 @comment LocalWords: bigrams cd chmod comp crc CVS dbfile dum eof
5112 @comment LocalWords: fileserver filesystem fn frcode Ghazi Hnewc iXX
5113 @comment LocalWords: joeuser Kaveh localpaths localuser LOGNAME
5114 @comment LocalWords: Meyering mv netpaths netuser nonblank nonblanks
5115 @comment LocalWords: ois ok Pinard printindex proc procs prunefs
5116 @comment LocalWords: prunepaths pwd RFS rmadillo rmdir rsh sbins str
5117 @comment LocalWords: su Timar ubins ug unstripped vf VM Weitzel
5118 @comment LocalWords: wildcard zlogout basename execdir wholename iwholename
5119 @comment LocalWords: timestamp timestamps Solaris FreeBSD OpenBSD POSIX