Import wcwidth (not wvwidth, which was a typo in the previous change)
[findutils.git] / doc / find.texi
blob007f8808c6426583f63b9a962467c09676307bdd
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 Free
35 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 @menu
150 * Scope::
151 * Overview::
152 * find Expressions::
153 @end menu
155 @node Scope
156 @section Scope
158 For brevity, the word @dfn{file} in this manual means a regular file,
159 a directory, a symbolic link, or any other kind of node that has a
160 directory entry.  A directory entry is also called a @dfn{file name}.
161 A file name may contain some, all, or none of the directories in a
162 path that leads to the file.  These are all examples of what this
163 manual calls ``file names'':
165 @example
166 parser.c
167 README
168 ./budget/may-94.sc
169 fred/.cshrc
170 /usr/local/include/termcap.h
171 @end example
173 A @dfn{directory tree} is a directory and the files it contains, all
174 of its subdirectories and the files they contain, etc.  It can also be
175 a single non-directory file.
177 These programs enable you to find the files in one or more directory
178 trees that:
180 @itemize @bullet
181 @item
182 have names that contain certain text or match a certain pattern;
183 @item
184 are links to certain files;
185 @item
186 were last used during a certain period of time;
187 @item
188 are within a certain size range;
189 @item
190 are of a certain type (regular file, directory, symbolic link, etc.);
191 @item
192 are owned by a certain user or group;
193 @item
194 have certain access permissions or special mode bits;
195 @item
196 contain text that matches a certain pattern;
197 @item
198 are within a certain depth in the directory tree;
199 @item
200 or some combination of the above.
201 @end itemize
203 Once you have found the files you're looking for (or files that are
204 potentially the ones you're looking for), you can do more to them than
205 simply list their names.  You can get any combination of the files'
206 attributes, or process the files in many ways, either individually or
207 in groups of various sizes.  Actions that you might want to perform on
208 the files you have found include, but are not limited to:
210 @itemize @bullet
211 @item
212 view or edit
213 @item
214 store in an archive
215 @item
216 remove or rename
217 @item
218 change access permissions
219 @item
220 classify into groups
221 @end itemize
223 This manual describes how to perform each of those tasks, and more.
225 @node Overview
226 @section Overview
228 The principal programs used for making lists of files that match given
229 criteria and running commands on them are @code{find}, @code{locate},
230 and @code{xargs}.  An additional command, @code{updatedb}, is used by
231 system administrators to create databases for @code{locate} to use.
233 @code{find} searches for files in a directory hierarchy and prints
234 information about the files it found.  It is run like this:
236 @example
237 find @r{[}@var{file}@dots{}@r{]} @r{[}@var{expression}@r{]}
238 @end example
240 @noindent
241 Here is a typical use of @code{find}.  This example prints the names
242 of all files in the directory tree rooted in @file{/usr/src} whose
243 name ends with @samp{.c} and that are larger than 100 Kilobytes.
244 @example
245 find /usr/src -name '*.c' -size +100k -print
246 @end example
248 Notice that the wildcard must be enclosed in quotes in order to
249 protect it from expansion by the shell.
251 @code{locate} searches special file name databases for file names that
252 match patterns.  The system administrator runs the @code{updatedb}
253 program to create the databases.  @code{locate} is run like this:
255 @example
256 locate @r{[}@var{option}@dots{}@r{]} @var{pattern}@dots{}
257 @end example
259 @noindent
260 This example prints the names of all files in the default file name
261 database whose name ends with @samp{Makefile} or @samp{makefile}.
262 Which file names are stored in the database depends on how the system
263 administrator ran @code{updatedb}.
264 @example
265 locate '*[Mm]akefile'
266 @end example
268 The name @code{xargs}, pronounced EX-args, means ``combine
269 arguments.''  @code{xargs} builds and executes command lines by
270 gathering together arguments it reads on the standard input.  Most
271 often, these arguments are lists of file names generated by
272 @code{find}.  @code{xargs} is run like this:
274 @example
275 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
276 @end example
278 @noindent
279 The following command searches the files listed in the file
280 @file{file-list} and prints all of the lines in them that contain the
281 word @samp{typedef}.
282 @example
283 xargs grep typedef < file-list
284 @end example
286 @node find Expressions
287 @section @code{find} Expressions
289 The expression that @code{find} uses to select files consists of one
290 or more @dfn{primaries}, each of which is a separate command line
291 argument to @code{find}.  @code{find} evaluates the expression each
292 time it processes a file.  An expression can contain any of the
293 following types of primaries:
295 @table @dfn
296 @item options
297 affect overall operation rather than the processing of a specific
298 file;
299 @item tests
300 return a true or false value, depending on the file's attributes;
301 @item actions
302 have side effects and return a true or false value; and
303 @item operators
304 connect the other arguments and affect when and whether they are
305 evaluated.
306 @end table
308 You can omit the operator between two primaries; it defaults to
309 @samp{-and}.  @xref{Combining Primaries With Operators}, for ways to
310 connect primaries into more complex expressions.  If the expression
311 contains no actions other than @samp{-prune}, @samp{-print} is
312 performed on all files for which the entire expression is true
313 (@pxref{Print File Name}).
315 Options take effect immediately, rather than being evaluated for each
316 file when their place in the expression is reached.  Therefore, for
317 clarity, it is best to place them at the beginning of the expression.
318 There are two exceptions to this; @samp{-daystart} and @samp{-follow}
319 have different effects depending on where in the command line they
320 appear.  This can be confusing, so it's best to keep them at the
321 beginning, too.
323 Many of the primaries take arguments, which immediately follow them in
324 the next command line argument to @code{find}.  Some arguments are
325 file names, patterns, or other strings; others are numbers.  Numeric
326 arguments can be specified as
328 @table @code
329 @item +@var{n}
330 for greater than @var{n},
331 @item -@var{n}
332 for less than @var{n},
333 @item @var{n}
334 for exactly @var{n}.
335 @end table
337 @node Finding Files
338 @chapter Finding Files
340 By default, @code{find} prints to the standard output the names of the
341 files that match the given criteria.  @xref{Actions}, for how to get
342 more information about the matching files.
345 @menu
346 * Name::
347 * Links::
348 * Time::
349 * Size::
350 * Type::
351 * Owner::
352 * Mode Bits::
353 * Contents::
354 * Directories::
355 * Filesystems::
356 * Combining Primaries With Operators::
357 @end menu
359 @node Name
360 @section Name
362 Here are ways to search for files whose name matches a certain
363 pattern.  @xref{Shell Pattern Matching}, for a description of the
364 @var{pattern} arguments to these tests.
366 Each of these tests has a case-sensitive version and a
367 case-insensitive version, whose name begins with @samp{i}.  In a
368 case-insensitive comparison, the patterns @samp{fo*} and @samp{F??}
369 match the file names @file{Foo}, @samp{FOO}, @samp{foo}, @samp{fOo},
370 etc.
372 @menu
373 * Base Name Patterns::
374 * Full Name Patterns::
375 * Fast Full Name Search::
376 * Shell Pattern Matching::      Wildcards used by these programs.
377 @end menu
379 @node Base Name Patterns
380 @subsection Base Name Patterns
382 @deffn Test -name pattern
383 @deffnx Test -iname pattern
384 True if the base of the file name (the path with the leading
385 directories removed) matches shell pattern @var{pattern}.  For
386 @samp{-iname}, the match is case-insensitive.@footnote{Because we
387 need to perform case-insensitive matching, the GNU fnmatch
388 implementation is always used; if the C library includes the GNU
389 implementation, we use that and otherwise we use the one from gnulib}
390 To ignore a whole directory tree, use @samp{-prune}
391 (@pxref{Directories}).  As an example, to find Texinfo source files in
392 @file{/usr/local/doc}:
394 @example
395 find /usr/local/doc -name '*.texi'
396 @end example
398 Notice that the wildcard must be enclosed in quotes in order to
399 protect it from expansion by the shell.
401 As of findutils version 4.2.2, patterns for @samp{-name} and
402 @samp{-iname} will match a file name with a leading @samp{.}.  For
403 example the command @samp{find /tmp -name \*bar} will match the file
404 @file{/tmp/.foobar}.  Braces within the pattern (@samp{@{@}}) are not
405 considered to be special (that is, @code{find . -name 'foo@{1,2@}'}
406 matches a file named @file{foo@{1,2@}}, not the files @file{foo1} and
407 @file{foo2}.
408 @end deffn
411 @node Full Name Patterns
412 @subsection Full Name Patterns
414 @deffn Test -wholename pattern
415 @deffnx Test -iwholename pattern
416 True if the entire file name, starting with the command line argument
417 under which the file was found, matches shell pattern @var{pattern}.
418 For @samp{-iwholename}, the match is case-insensitive.  To ignore a
419 whole directory tree, use @samp{-prune} rather than checking every
420 file in the tree (@pxref{Directories}).  The ``entire file name'' as
421 used by @code{find} starts with the starting-point specified on the
422 command line, and is not converted to an absolute pathname, so for
423 example @code{cd /; find tmp -wholename /tmp} will never match
424 anything.
425 @end deffn
427 @deffn Test -path pattern
428 @deffnx Test -ipath pattern
429 These tests are deprecated, but work as for @samp{-wholename} and
430 @samp{-iwholename}, respectively.  The @samp{-ipath} test is a GNU
431 extension, but @samp{-path} is also provided by HP-UX @code{find}.
432 @end deffn
434 @deffn Test -regex expr
435 @deffnx Test -iregex expr
436 True if the entire file name matches regular expression @var{expr}.
437 This is a match on the whole path, not a search.  For example, to
438 match a file named @file{./fubar3}, you can use the regular expression
439 @samp{.*bar.} or @samp{.*b.*3}, but not @samp{f.*r3}.  @xref{Regexps,
440 , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}, for a
441 description of the syntax of regular expressions.  For @samp{-iregex},
442 the match is case-insensitive.  There are several varieties of regular
443 expressions; by default this test uses POSIX basic regular
444 expressions, but this can be changed with the option
445 @samp{-regextype}.
446 @end deffn
448 @deffn Option -regextype name
449 This option controls the variety of regular expression syntax
450 understood by the @samp{-regex} and @samp{-iregex} tests.  This option
451 is positional; that is, it only affects regular expressions which
452 occur later in the command line.  If this option is not given, GNU
453 Emacs regular expressions are assumed.  Currently-implemented types
457 @table @samp
458 @item emacs
459 Regular expressions compatible with GNU Emacs; this is also the
460 default behaviour if this option is not used.
461 @item posix-awk
462 Regular expressions compatible with the POSIX awk command (not GNU awk)
463 @item posix-basic
464 POSIX Basic Regular Expressions.
465 @item posix-egrep
466 Regular expressions compatible with the POSIX egrep command
467 @item posix-extended
468 POSIX Extended Regular Expressions
469 @end table
471 @ref{Regular Expressions} for more information on the regular
472 expression dialects understood by GNU findutils.
475 @end deffn
477 @node Fast Full Name Search
478 @subsection Fast Full Name Search
480 To search for files by name without having to actually scan the
481 directories on the disk (which can be slow), you can use the
482 @code{locate} program.  For each shell pattern you give it,
483 @code{locate} searches one or more databases of file names and
484 displays the file names that contain the pattern.  @xref{Shell Pattern
485 Matching}, for details about shell patterns.
487 If a pattern is a plain string---it contains no
488 metacharacters---@code{locate} displays all file names in the database
489 that contain that string.  If a pattern contains
490 metacharacters, @code{locate} only displays file names that match the
491 pattern exactly.  As a result, patterns that contain metacharacters
492 should usually begin with a @samp{*}, and will most often end with one
493 as well.  The exceptions are patterns that are intended to explicitly
494 match the beginning or end of a file name.
496 If you only want @code{locate} to match against the last component of
497 the file names (the ``base name'' of the files) you can use the
498 @samp{--basename} option.  The opposite behaviour is the default, but
499 can be selected explicitly by using the option @samp{--wholename}.
501 The command
502 @example
503 locate @var{pattern}
504 @end example
506 is almost equivalent to
507 @example
508 find @var{directories} -name @var{pattern}
509 @end example
511 where @var{directories} are the directories for which the file name
512 databases contain information.  The differences are that the
513 @code{locate} information might be out of date, and that @code{locate}
514 handles wildcards in the pattern slightly differently than @code{find}
515 (@pxref{Shell Pattern Matching}).
517 The file name databases contain lists of files that were on the system
518 when the databases were last updated.  The system administrator can
519 choose the file name of the default database, the frequency with which
520 the databases are updated, and the directories for which they contain
521 entries.
523 Here is how to select which file name databases @code{locate}
524 searches.  The default is system-dependent.  At the time this document
525 was generated, the default was @file{@value{LOCATE_DB}}.
527 @table @code
528 @item --database=@var{path}
529 @itemx -d @var{path}
530 Instead of searching the default file name database, search the file
531 name databases in @var{path}, which is a colon-separated list of
532 database file names.  You can also use the environment variable
533 @code{LOCATE_PATH} to set the list of database files to search.  The
534 option overrides the environment variable if both are used.
535 @end table
537 GNU @code{locate} can read file name databases generated by the
538 @code{slocate} package.  However, these generally contain a list of
539 all the files on the system, and so when using this database,
540 @code{locate} will produce output only for files which are accessible
541 to you.  @xref{Invoking locate}, for a description of the
542 @samp{--existing} option which is used to do this.
544 The @code{updatedb} program can also generate database in a format
545 compatible with @code{slocate}.  @xref{Invoking updatedb}, for a
546 description of its @samp{--dbformat} and @samp{--output} options.
549 @node Shell Pattern Matching
550 @subsection Shell Pattern Matching
552 @code{find} and @code{locate} can compare file names, or parts of file
553 names, to shell patterns.  A @dfn{shell pattern} is a string that may
554 contain the following special characters, which are known as
555 @dfn{wildcards} or @dfn{metacharacters}.
557 You must quote patterns that contain metacharacters to prevent the
558 shell from expanding them itself.  Double and single quotes both work;
559 so does escaping with a backslash.
561 @table @code
562 @item *
563 Matches any zero or more characters.
565 @item ?
566 Matches any one character.
568 @item [@var{string}]
569 Matches exactly one character that is a member of the string
570 @var{string}.  This is called a @dfn{character class}.  As a
571 shorthand, @var{string} may contain ranges, which consist of two
572 characters with a dash between them.  For example, the class
573 @samp{[a-z0-9_]} matches a lowercase letter, a number, or an
574 underscore.  You can negate a class by placing a @samp{!} or @samp{^}
575 immediately after the opening bracket.  Thus, @samp{[^A-Z@@]} matches
576 any character except an uppercase letter or an at sign.
578 @item \
579 Removes the special meaning of the character that follows it.  This
580 works even in character classes.
581 @end table
583 In the @code{find} tests that do shell pattern matching (@samp{-name},
584 @samp{-wholename}, etc.), wildcards in the pattern will match a
585 @samp{.}  at the beginning of a file name.  This is also the case for
586 @code{locate}.  Thus, @samp{find -name '*macs'} will match a file
587 named @file{.emacs}, as will @samp{locate '*macs'}.
589 Slash characters have no special significance in the shell pattern
590 matching that @code{find} and @code{locate} do, unlike in the shell,
591 in which wildcards do not match them.  Therefore, a pattern
592 @samp{foo*bar} can match a file name @samp{foo3/bar}, and a pattern
593 @samp{./sr*sc} can match a file name @samp{./src/misc}.
595 If you want to locate some files with the @samp{locate} command but
596 don't need to see the full list you can use the @samp{--limit} option
597 to see just a small number of results, or the @samp{--count} option to
598 display only the total number of matches.
600 @node Links
601 @section Links
603 There are two ways that files can be linked together.  @dfn{Symbolic
604 links} are a special type of file whose contents are a portion of the
605 name of another file.  @dfn{Hard links} are multiple directory entries
606 for one file; the file names all have the same index node
607 (@dfn{inode}) number on the disk.
609 @menu
610 * Symbolic Links::
611 * Hard Links::
612 @end menu
614 @node Symbolic Links
615 @subsection Symbolic Links
617 Symbolic links are names that reference other files.  GNU @code{find}
618 will handle symbolic links in one of two ways; firstly, it can
619 dereference the links for you - this means that if it comes across a
620 symbolic link, it examines the file that the link points to, in order
621 to see if it matches the criteria you have specified.  Secondly, it
622 can check the link itself in case you might be looking for the actual
623 link.  If the file that the symbolic link points to is also within the
624 directory hierarchy you are searching with the @code{find} command,
625 you may not see a great deal of difference between these two
626 alternatives.
628 By default, @code{find} examines symbolic links themselves when it
629 finds them (and, if it later comes across the linked-to file, it will
630 examine that, too).  If you would prefer @code{find} to dereference
631 the links and examine the file that each link points to, specify the
632 @samp{-L} option to @code{find}.  You can explicitly specify the
633 default behaviour by using the @samp{-P} option.  The @samp{-H}
634 option is a half-way-between option which ensures that any symbolic
635 links listed on the command line are dereferenced, but other symbolic
636 links are not.
638 Symbolic links are different to ``hard links'' in the sense that you
639 need permission to search the directories
640 in the linked-to file name to
641 dereference the link.  This can mean that even if you specify the
642 @samp{-L} option, @code{find} may not be able to determine the
643 properties of the file that the link points to (because you don't have
644 sufficient permission).  In this situation, @code{find} uses the
645 properties of the link itself.  This also occurs if a symbolic link
646 exists but points to a file that is missing.
648 The options controlling the behaviour of @code{find} with respect to
649 links are as follows :-
651 @table @samp
652 @item -P
653 @code{find} does not dereference symbolic links at all.  This is the
654 default behaviour.  This option must be specified before any of the
655 file names on the command line.
656 @item -H
657 @code{find} does not dereference symbolic links (except in the case of
658 file names on the command line, which are dereferenced).  If a
659 symbolic link cannot be dereferenced, the information for the symbolic
660 link itself is used.  This option must be specified before any of the
661 file names on the command line.
662 @item -L
663 @code{find} dereferences symbolic links where possible, and where this
664 is not possible it uses the properties of the symbolic link itself.
665 This option must be specified before any of the file names on the
666 command line.  Use of this option also implies the same behaviour as
667 the @samp{-noleaf} option.  If you later use the @samp{-H} or
668 @samp{-P} options, this does not turn off @samp{-noleaf}.
670 @item -follow
671 This option forms part of the ``expression'' and must be specified
672 after the file names, but it is otherwise equivalent to @samp{-L}.
673 The @samp{-follow} option affects only those tests which appear after
674 it on the command line.  This option is deprecated.  Where possible,
675 you should use @samp{-L} instead.
676 @end table
678 The following differences in behavior occur when the @samp{-L} option
679 is used:
681 @itemize @bullet
682 @item
683 @code{find} follows symbolic links to directories when searching
684 directory trees.
685 @item
686 @samp{-lname} and @samp{-ilname} always return false (unless they
687 happen to match broken symbolic links).
688 @item
689 @samp{-type} reports the types of the files that symbolic links point
690 to.  This means that in combination with @samp{-L}, @samp{-type l}
691 will be true only for broken symbolic links.  To check for symbolic
692 links when @samp{-L} has been specified, use @samp{-xtype l}.
693 @item
694 Implies @samp{-noleaf} (@pxref{Directories}).
695 @end itemize
697 If the @samp{-L} option or the @samp{-H} option is used,
698 the file names used as arguments to @samp{-newer}, @samp{-anewer}, and
699 @samp{-cnewer} are dereferenced and the timestamp from the pointed-to
700 file is used instead (if possible -- otherwise the timestamp from the
701 symbolic link is used).
703 @deffn Test -lname pattern
704 @deffnx Test -ilname pattern
705 True if the file is a symbolic link whose contents match shell pattern
706 @var{pattern}.  For @samp{-ilname}, the match is case-insensitive.
707 @xref{Shell Pattern Matching}, for details about the @var{pattern}
708 argument.  If the @samp{-L} option is in effect, this test will always
709 return false for symbolic links unless they are broken.  So, to list
710 any symbolic links to @file{sysdep.c} in the current directory and its
711 subdirectories, you can do:
713 @example
714 find . -lname '*sysdep.c'
715 @end example
716 @end deffn
718 @node Hard Links
719 @subsection Hard Links
721 Hard links allow more than one name to refer to the same file.  To
722 find all the names which refer to the same file as NAME, use
723 @samp{-samefile NAME}.  If you are not using the @samp{-L} option, you
724 can confine your search to one filesystem using the @samp{-xdev}
725 option.  This is useful because hard links cannot point outside a
726 single filesystem, so this can cut down on needless searching.
728 If the @samp{-L} option is in effect, and NAME is in fact a symbolic
729 link, the symbolic link will be dereferenced.  Hence you are searching
730 for other links (hard or symbolic) to the file pointed to by NAME.  If
731 @samp{-L} is in effect but NAME is not itself a symbolic link, other
732 symbolic links to the file NAME will be matched.
734 You can also search for files by inode number.  This can occasionally
735 be useful in diagnosing problems with filesystems for example, because
736 @code{fsck} tends to print inode numbers.  Inode numbers also
737 occasionally turn up in log messages for some types of software, and
738 are used to support the @code{ftok()} library function.
740 You can learn a file's inode number and the number of links to it by
741 running @samp{ls -li} or @samp{find -ls}.
743 You can search for hard links to inode number NUM by using @samp{-inum
744 NUM}. If there are any filesystem mount points below the directory
745 where you are starting the search, use the @samp{-xdev} option unless
746 you are also using the @samp{-L} option.  Using @samp{-xdev} this
747 saves needless searching, since hard links to a file must be on the
748 same filesystem.  @xref{Filesystems}.
750 @deffn Test -samefile NAME
751 File is a hard link to the same inode as NAME.  If the @samp{-L}
752 option is in effect, symbolic links to the same file as NAME points to
753 are also matched.
754 @end deffn
756 @deffn Test -inum n
757 File has inode number @var{n}.  The @samp{+} and @samp{-} qualifiers
758 also work, though these are rarely useful.  Much of the time it is
759 easier to use @samp{-samefile} rather than this option.
760 @end deffn
762 You can also search for files that have a certain number of links,
763 with @samp{-links}.  Directories normally have at least two hard
764 links; their @file{.} entry is the second one.  If they have
765 subdirectories, each of those also has a hard link called @file{..} to
766 its parent directory.  The @file{.} and @file{..} directory entries
767 are not normally searched unless they are mentioned on the @code{find}
768 command line.
770 @deffn Test -links n
771 File has @var{n} hard links.
772 @end deffn
774 @deffn Test -links +n
775 File has more than @var{n} hard links.
776 @end deffn
778 @deffn Test -links -n
779 File has fewer than @var{n} hard links.
780 @end deffn
782 @node Time
783 @section Time
785 Each file has three time stamps, which record the last time that
786 certain operations were performed on the file:
788 @enumerate
789 @item
790 access (read the file's contents)
791 @item
792 change the status (modify the file or its attributes)
793 @item
794 modify (change the file's contents)
795 @end enumerate
797 Some systems also provide a timestamp that indicates when a file was
798 @emph{created}.   For example, the UFS2 fileystem under NetBSD-3.1
799 records the @emph{birth time} of each file.  This information is also
800 available under other versions of BSD and some versions of Cygwin.
801 However, even on systems which support file birth time, files may
802 exist for which this information was not recorded (for example, UFS1
803 file systems simply do not contain this information).
805 You can search for files whose time stamps are within a certain age
806 range, or compare them to other time stamps.
808 @menu
809 * Age Ranges::
810 * Comparing Timestamps::
811 @end menu
813 @node Age Ranges
814 @subsection Age Ranges
816 These tests are mainly useful with ranges (@samp{+@var{n}} and
817 @samp{-@var{n}}).
819 @deffn Test -atime n
820 @deffnx Test -ctime n
821 @deffnx Test -mtime n
822 True if the file was last accessed (or its status changed, or it was
823 modified) @var{n}*24 hours ago.  The number of 24-hour periods since
824 the file's timestamp is always rounded down; therefore 0 means ``less
825 than 24 hours ago'', 1 means ``between 24 and 48 hours ago'', and so
826 forth.  Fractional values are supported but this only really makes
827 sense for the case where ranges (@samp{+@var{n}} and @samp{-@var{n}})
828 are used.
829 @end deffn
831 @deffn Test -amin n
832 @deffnx Test -cmin n
833 @deffnx Test -mmin n
834 True if the file was last accessed (or its status changed, or it was
835 modified) @var{n} minutes ago.  These tests provide finer granularity
836 of measurement than @samp{-atime} et al., but rounding is done in a
837 similar way (again, fractions are supported).  For example, to list
838 files in @file{/u/bill} that were last read from 2 to 6 minutes ago:
840 @example
841 find /u/bill -amin +2 -amin -6
842 @end example
843 @end deffn
845 @deffn Option -daystart
846 Measure times from the beginning of today rather than from 24 hours
847 ago.  So, to list the regular files in your home directory that were
848 modified yesterday, do
850 @example
851 find ~/ -daystart -type f -mtime 1
852 @end example
854 The @samp{-daystart} option is unlike most other options in that it
855 has an effect on the way that other tests are performed.  The affected
856 tests are @samp{-amin}, @samp{-cmin}, @samp{-mmin}, @samp{-atime},
857 @samp{-ctime} and @samp{-mtime}.  The @samp{-daystart} option only
858 affects the behaviour of any tests which appear after it on the
859 command line.
860 @end deffn
862 @node Comparing Timestamps
863 @subsection Comparing Timestamps
865 @deffn Test -newerXY reference
866 Succeeds if timestamp @samp{X} of the file being considered is newer
867 than timestamp @samp{Y} of the file @file{reference}.   The latters
868 @samp{X} and @samp{Y} can be any of the following letters:
870 @table @samp
871 @item a
872 Last-access time of @file{reference}
873 @item B
874 Birth time of @file{reference} (when this is not known, the test cannot succeed)
875 @item c
876 Last-change time of @file{reference}
877 @item m
878 Last-modification time of @file{reference}
879 @item t
880 The @file{reference} argument is interpreted as a literal time, rather
881 than the name of a file.  @xref{Date input formats}, for a description
882 of how the timestamp is understood.  Tests of the form @samp{-newerXt}
883 are valid but tests of the form @samp{-newertY} are not.
884 @end table
886 For example the test @code{-newerac /tmp/foo} succeeds for all files
887 which have been accessed more recently than @file{/tmp/foo} was
888 changed.   Here @samp{X} is @samp{a} and @samp{Y} is @samp{c}.   
890 Not all files have a known birth time.  If @samp{Y} is @samp{b} and
891 the birth time of @file{reference} is not available, @code{find} exits
892 with an explanatory error message.  If @samp{X} is @samp{b} and we do
893 not know the birth time the file currently being considered, the test
894 simply fails (that is, it behaves like @code{-false} does).
896 Some operating systems (for example, most implementations of Unix) do
897 not support file birth times.  Some others, for example NetBSD-3.1,
898 do.  Even on operating systems which support file birth times, the
899 information may not be available for specific files.  For example,
900 under NetBSD, file birth times are supported on UFS2 file systems, but
901 not UFS1 file systems.
903 @end deffn
907 There are two ways to list files in @file{/usr} modified after
908 February 1 of the current year.  One uses @samp{-newermt}:
910 @example
911 find /usr -newermt "Feb 1"
912 @end example
914 The other way of doing this works on the versions of find before 4.3.3:
916 @c Idea from Rick Sladkey.
917 @example
918 touch -t 02010000 /tmp/stamp$$
919 find /usr -newer /tmp/stamp$$
920 rm -f /tmp/stamp$$
921 @end example
923 @deffn Test -anewer file
924 @deffnx Test -cnewer file
925 @deffnx Test -newer file
926 True if the file was last accessed (or its status changed, or it was
927 modified) more recently than @var{file} was modified.  These tests are
928 affected by @samp{-follow} only if @samp{-follow} comes before them on
929 the command line.  @xref{Symbolic Links}, for more information on
930 @samp{-follow}.  As an example, to list any files modified since
931 @file{/bin/sh} was last modified:
933 @example
934 find . -newer /bin/sh
935 @end example
936 @end deffn
938 @deffn Test -used n
939 True if the file was last accessed @var{n} days after its status was
940 last changed.  Useful for finding files that are not being used, and
941 could perhaps be archived or removed to save disk space.
942 @end deffn
944 @node Size
945 @section Size
947 @deffn Test -size n@r{[}bckwMG@r{]}
948 True if the file uses @var{n} units of space, rounding up.  The units
949 are 512-byte blocks by default, but they can be changed by adding a
950 one-character suffix to @var{n}:
952 @table @code
953 @item b
954 512-byte blocks (never 1024)
955 @item c
956 bytes
957 @item k
958 kilobytes (1024 bytes)
959 @item w
960 2-byte words
961 @item M
962 Megabytes (units of 1048576 bytes)
963 @item G
964 Gigabytes (units of 1073741824 bytes)
965 @end table
967 The `b' suffix always considers blocks to be 512 bytes.  This is not
968 affected by the setting (or non-setting) of the POSIXLY_CORRECT
969 environment variable.  This behaviour is different to the behaviour of
970 the @samp{-ls} action).  If you want to use 1024-byte units, use the
971 `k' suffix instead.
973 The number can be prefixed with a `+' or a `-'.  A plus sign indicates
974 that the test should succeed if the file uses at least @var{n} units
975 of storage (a common use of this test) and a minus sign
976 indicates that the test should succeed if the file uses less than
977 @var{n} units of storage.  There is no `=' prefix, because that's the
978 default anyway.
980 The size does not count indirect blocks, but it does count blocks in
981 sparse files that are not actually allocated.  In other words, it's
982 consistent with the result you get for @samp{ls -l} or @samp{wc -c}.
983 This handling of sparse files differs from the output of the @samp{%k}
984 and @samp{%b} format specifiers for the @samp{-printf} predicate.
986 @end deffn
988 @deffn Test -empty
989 True if the file is empty and is either a regular file or a directory.
990 This might help determine good candidates for deletion.  This test is
991 useful with @samp{-depth} (@pxref{Directories}) and @samp{-delete}
992 (@pxref{Single File}).
993 @end deffn
995 @node Type
996 @section Type
998 @deffn Test -type c
999 True if the file is of type @var{c}:
1001 @table @code
1002 @item b
1003 block (buffered) special
1004 @item c
1005 character (unbuffered) special
1006 @item d
1007 directory
1008 @item p
1009 named pipe (FIFO)
1010 @item f
1011 regular file
1012 @item l
1013 symbolic link; if @samp{-L} is in effect, this is true only for broken
1014 symbolic links.  If you want to search for symbolic links when
1015 @samp{-L} is in effect, use @samp{-xtype} instead of @samp{-type}.
1016 @item s
1017 socket
1018 @item D
1019 door (Solaris)
1020 @end table
1021 @end deffn
1023 @deffn Test -xtype c
1024 This test behaves the same as @samp{-type} unless the file is a
1025 symbolic link.  If the file is a symbolic link, the result is as
1026 follows (in the table below, @samp{X} should be understood to
1027 represent any letter except @samp{l}):
1029 @table @samp
1030 @item @samp{-P -xtype l}
1031 True if the symbolic link is broken
1032 @item @samp{-P -xtype X}
1033 True if the (ultimate) target file is of type @samp{X}.
1034 @item @samp{-L -xtype l}
1035 Always true
1036 @item @samp{-L -xtype X}
1037 False unless the symbolic link is broken
1038 @end table
1040 In other words, for symbolic links, @samp{-xtype} checks the type of
1041 the file that @samp{-type} does not check.  
1043 The @samp{-H} option also affects the behaviour of @samp{-xtype}.
1044 When @samp{-H} is in effect, @samp{-xtype} behaves as if @samp{-L} had
1045 been specified when examining files listed on the command line, and as
1046 if @samp{-P} had been specified otherwise.  If neither @samp{-H} nor
1047 @samp{-L} was specified, @samp{-xtype} behaves as if @samp{-P} had
1048 been specified.
1050 @xref{Symbolic Links}, for more information on @samp{-follow} and
1051 @samp{-L}.
1052 @end deffn
1054 @node Owner
1055 @section Owner
1057 @deffn Test -user uname
1058 @deffnx Test -group gname
1059 True if the file is owned by user @var{uname} (belongs to group
1060 @var{gname}).  A numeric ID is allowed.
1061 @end deffn
1063 @deffn Test -uid n
1064 @deffnx Test -gid n
1065 True if the file's numeric user ID (group ID) is @var{n}.  These tests
1066 support ranges (@samp{+@var{n}} and @samp{-@var{n}}), unlike
1067 @samp{-user} and @samp{-group}.
1068 @end deffn
1070 @deffn Test -nouser
1071 @deffnx Test -nogroup
1072 True if no user corresponds to the file's numeric user ID (no group
1073 corresponds to the numeric group ID).  These cases usually mean that
1074 the files belonged to users who have since been removed from the
1075 system.  You probably should change the ownership of such files to an
1076 existing user or group, using the @code{chown} or @code{chgrp}
1077 program.
1078 @end deffn
1080 @node Mode Bits
1081 @section File Mode Bits
1083 @xref{File Permissions}, for information on how file mode bits are
1084 structured and how to specify them.
1086 Four tests determine what users can do with files.  These are
1087 @samp{-readable}, @samp{-writable}, @samp{-executable} and
1088 @samp{-perm}.  The first three tests ask the operating system if the
1089 current user can perform the relevant operation on a file, while
1090 @samp{-perm} just examines the file's mode.  The file mode may give
1091 a misleading impression of what the user can actually do, because the
1092 file may have an access control list, or exist on a read-only
1093 filesystem, for example.  Of these four tests though, only
1094 @samp{-perm} is specified by the POSIX standard.
1096 The @samp{-readable}, @samp{-writable} and @samp{-executable} tests
1097 are implemented via the @code{access} system call.  This is
1098 implemented within the operating system itself.  If the file being
1099 considered is on an NFS filesystem, the remote system may allow or
1100 forbid read or write operations for reasons of which the NFS client
1101 cannot take account.  This includes user-ID mapping, either in the
1102 general sense or the more restricted sense in which remote superusers
1103 are treated by the NFS server as if they are the local user
1104 @samp{nobody} on the NFS server.
1106 None of the tests in this section should be used to verify that a user
1107 is authorised to perform any operation (on the file being tested or
1108 any other file) because of the possibility of a race condition.  That
1109 is, the situation may change between the test and an action being
1110 taken on the basis of the result of that test.
1113 @deffn Test -readable 
1114 True if the file can be read by the invoking user.
1115 @end deffn
1117 @deffn Test -writable
1118 True if the file can be written by the invoking user.  This is an
1119 in-principle check, and other things may prevent a successful write
1120 operation; for example, the filesystem might be full.
1121 @end deffn
1123 @deffn Test -executable
1124 True if the file can be executed/searched by the invoking user.
1125 @end deffn
1127 @deffn Test -perm pmode
1129 True if the file's mode bits match @var{pmode}, which can be
1130 either a symbolic or numeric @var{mode} (@pxref{File Permissions})
1131 optionally prefixed by @samp{-} or @samp{/}.
1133 A @var{pmode} that starts with neither @samp{-} nor @samp{/} matches
1134 if @var{mode} exactly matches the file mode bits.
1136 A @var{pmode} that starts with @samp{-} matches if
1137 @emph{all} the file mode bits set in @var{mode} are set for the file;
1138 bits not set in @var{mode} are ignored.
1140 A @var{pmode} that starts with @samp{/} matches if
1141 @emph{any} of the file mode bits set in @var{mode} are set for the file;
1142 bits not set in @var{mode} are ignored.
1143 This is a GNU extension.
1145 If you don't use the @samp{/} or @samp{-} form with a symbolic mode
1146 string, you may have to specify a rather complex mode string.  For
1147 example @samp{-perm g=w} will only match files that have mode 0020
1148 (that is, ones for which group write permission is the only file mode bit
1149 set).  It is more likely that you will want to use the @samp{/} or
1150 @samp{-} forms, for example @samp{-perm -g=w}, which matches any file
1151 with group write permission.
1154 @table @samp
1155 @item -perm 664
1156 Match files that have read and write permission for their owner,
1157 and group, but that the rest of the world can read but not write to.
1158 Do not match files that meet these criteria but have other file mode
1159 bits set (for example if someone can execute/search the file).
1161 @item -perm -664
1162 Match files that have read and write permission for their owner,
1163 and group, but that the rest of the world can read but not write to,
1164 without regard to the presence of any extra file mode bits (for
1165 example the executable bit).  This matches a file with mode
1166 0777, for example.
1168 @item -perm /222
1169 Match files that are writable by somebody (their owner, or
1170 their group, or anybody else).
1172 @item -perm /022
1173 Match files that are writable by either their owner or their
1174 group.  The files don't have to be writable by both the owner and
1175 group to be matched; either will do.
1177 @item -perm /g+w,o+w
1178 As above.
1180 @item -perm /g=w,o=w
1181 As above.
1183 @item -perm -022
1184 Match files that are writable by both their owner and their
1185 group.
1187 @item -perm -444 -perm /222 ! -perm /111
1188 Match files that are readable for everybody, have at least one
1189 write bit set (i.e., somebody can write to them), but that cannot be
1190 executed/searched by anybody.  Note that in some shells the @samp{!} must be
1191 escaped;.
1193 @item -perm -a+r -perm /a+w ! -perm /a+x
1194 As above.
1197 @item -perm -g+w,o+w
1198 As above.
1199 @end table
1201 @quotation Warning
1202 If you specify @samp{-perm /000} or @samp{-perm /mode} where the
1203 symbolic mode @samp{mode} has no bits set, the test currently matches
1204 no files.  This differs from the behaviour of @samp{-perm -000}, which
1205 matches all files.  The behaviour of @samp{-perm /000} will be changed
1206 to be consistent with the behaviour of @samp{-perm -000}.  The change
1207 will probably be made in early 2006.
1208 @end quotation
1210 @end deffn
1212 @node Contents
1213 @section Contents
1215 To search for files based on their contents, you can use the
1216 @code{grep} program.  For example, to find out which C source files in
1217 the current directory contain the string @samp{thing}, you can do:
1219 @example
1220 grep -l thing *.[ch]
1221 @end example
1223 If you also want to search for the string in files in subdirectories,
1224 you can combine @code{grep} with @code{find} and @code{xargs}, like
1225 this:
1227 @example
1228 find . -name '*.[ch]' | xargs grep -l thing
1229 @end example
1231 The @samp{-l} option causes @code{grep} to print only the names of
1232 files that contain the string, rather than the lines that contain it.
1233 The string argument (@samp{thing}) is actually a regular expression,
1234 so it can contain metacharacters.  This method can be refined a little
1235 by using the @samp{-r} option to make @code{xargs} not run @code{grep}
1236 if @code{find} produces no output, and using the @code{find} action
1237 @samp{-print0} and the @code{xargs} option @samp{-0} to avoid
1238 misinterpreting files whose names contain spaces:
1240 @example
1241 find . -name '*.[ch]' -print0 | xargs -r -0 grep -l thing
1242 @end example
1244 For a fuller treatment of finding files whose contents match a
1245 pattern, see the manual page for @code{grep}.
1247 @node Directories
1248 @section Directories
1250 Here is how to control which directories @code{find} searches, and how
1251 it searches them.  These two options allow you to process a horizontal
1252 slice of a directory tree.
1254 @deffn Option -maxdepth levels
1255 Descend at most @var{levels} (a non-negative integer) levels of
1256 directories below the command line arguments.  @samp{-maxdepth 0}
1257 means only apply the tests and actions to the command line arguments.
1258 @end deffn
1260 @deffn Option -mindepth levels
1261 Do not apply any tests or actions at levels less than @var{levels} (a
1262 non-negative integer).  @samp{-mindepth 1} means process all files
1263 except the command line arguments.
1264 @end deffn
1266 @deffn Option -depth
1267 Process each directory's contents before the directory itself.  Doing
1268 this is a good idea when producing lists of files to archive with
1269 @code{cpio} or @code{tar}.  If a directory does not have write
1270 permission for its owner, its contents can still be restored from the
1271 archive since the directory's permissions are restored after its
1272 contents.
1273 @end deffn
1275 @deffn Option -d
1276 This is a deprecated synonym for @samp{-depth}, for compatibility with
1277 Mac OS X, FreeBSD and OpenBSD.  The @samp{-depth} option is a POSIX
1278 feature, so it is better to use that.
1279 @end deffn
1281 @deffn Action -prune
1282 If the file is a directory, do not descend into it.  The result is
1283 true.  For example, to skip the directory @file{src/emacs} and all
1284 files and directories under it, and print the names of the other files
1285 found:
1287 @example
1288 find . -wholename './src/emacs' -prune -o -print
1289 @end example
1291 The above command will not print @file{./src/emacs} among its list of
1292 results.  This however is not due to the effect of the @samp{-prune}
1293 action (which only prevents further descent, it doesn't make sure we
1294 ignore that item).  Instead, this effect is due to the use of
1295 @samp{-o}.  Since the left hand side of the ``or'' condition has
1296 succeeded for @file{./src/emacs}, it is not necessary to evaluate the
1297 right-hand-side (@samp{-print}) at all for this particular file.  If
1298 you wanted to print that directory name you could use either an extra
1299 @samp{-print} action:
1301 @example
1302 find . -wholename './src/emacs' -prune -print -o -print
1303 @end example
1305 or use the comma operator:
1307 @example
1308 find . -wholename './src/emacs' -prune , -print
1309 @end example
1311 If the @samp{-depth} option is in effect, the subdirectories will have
1312 already been visited in any case.  Hence @samp{-prune} has no effect
1313 and returns false.
1314 @end deffn
1317 @deffn Action -quit
1318 Exit immediately (with return value zero if no errors have occurred).
1319 No child processes will be left running, but no more files specified
1320 on the command line will be processed.  For example, @code{find
1321 /tmp/foo /tmp/bar -print -quit} will print only @samp{/tmp/foo}.  Any
1322 command lines which have been built by @samp{-exec ... \+} or
1323 @samp{-execdir ... \+} are invoked before the program is executed.
1324 @end deffn
1326 @deffn Option -noleaf
1327 Do not optimize by assuming that directories contain 2 fewer
1328 subdirectories than their hard link count.  This option is needed when
1329 searching filesystems that do not follow the Unix directory-link
1330 convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount
1331 points.  Each directory on a normal Unix filesystem has at least 2
1332 hard links: its name and its @file{.}  entry.  Additionally, its
1333 subdirectories (if any) each have a @file{..}  entry linked to that
1334 directory.  When @code{find} is examining a directory, after it has
1335 statted 2 fewer subdirectories than the directory's link count, it
1336 knows that the rest of the entries in the directory are
1337 non-directories (@dfn{leaf} files in the directory tree).  If only the
1338 files' names need to be examined, there is no need to stat them; this
1339 gives a significant increase in search speed.
1340 @end deffn
1342 @deffn Option -ignore_readdir_race
1343 If a file disappears after its name has been read from a directory but
1344 before @code{find} gets around to examining the file with @code{stat},
1345 don't issue an error message.  If you don't specify this option, an
1346 error message will be issued.  This option can be useful in system
1347 scripts (cron scripts, for example) that examine areas of the
1348 filesystem that change frequently (mail queues, temporary directories,
1349 and so forth), because this scenario is common for those sorts of
1350 directories.  Completely silencing error messages from @code{find} is
1351 undesirable, so this option neatly solves the problem.  There is no
1352 way to search one part of the filesystem with this option on and part
1353 of it with this option off, though.  When this option is turned on and 
1354 find discovers that one of the start-point files specified on the
1355 command line does not exist, no error message will be issued.
1357 @end deffn
1359 @deffn Option -noignore_readdir_race
1360 This option reverses the effect of the @samp{-ignore_readdir_race}
1361 option.
1362 @end deffn
1365 @node Filesystems
1366 @section Filesystems
1368 A @dfn{filesystem} is a section of a disk, either on the local host or
1369 mounted from a remote host over a network.  Searching network
1370 filesystems can be slow, so it is common to make @code{find} avoid
1371 them.
1373 There are two ways to avoid searching certain filesystems.  One way is
1374 to tell @code{find} to only search one filesystem:
1376 @deffn Option -xdev
1377 @deffnx Option -mount
1378 Don't descend directories on other filesystems.  These options are
1379 synonyms.
1380 @end deffn
1382 The other way is to check the type of filesystem each file is on, and
1383 not descend directories that are on undesirable filesystem types:
1385 @deffn Test -fstype type
1386 True if the file is on a filesystem of type @var{type}.  The valid
1387 filesystem types vary among different versions of Unix; an incomplete
1388 list of filesystem types that are accepted on some version of Unix or
1389 another is:
1390 @example
1391 ext2 ext3 proc sysfs ufs 4.2 4.3 nfs tmp mfs S51K S52K
1392 @end example
1393 You can use @samp{-printf} with the @samp{%F} directive to see the
1394 types of your filesystems.  The @samp{%D} directive shows the device
1395 number.  @xref{Print File Information}.  @samp{-fstype} is usually
1396 used with @samp{-prune} to avoid searching remote filesystems
1397 (@pxref{Directories}).
1398 @end deffn
1400 @node Combining Primaries With Operators
1401 @section Combining Primaries With Operators
1403 Operators build a complex expression from tests and actions.
1404 The operators are, in order of decreasing precedence:
1406 @table @code
1407 @item @asis{( @var{expr} )}
1408 @findex ()
1409 Force precedence.  True if @var{expr} is true.
1411 @item @asis{! @var{expr}}
1412 @itemx @asis{-not @var{expr}}
1413 @findex !
1414 @findex -not
1415 True if @var{expr} is false.  In some shells, it is necessary to
1416 protect the @samp{!} from shell interpretation by quoting it.
1418 @item @asis{@var{expr1 expr2}}
1419 @itemx @asis{@var{expr1} -a @var{expr2}}
1420 @itemx @asis{@var{expr1} -and @var{expr2}}
1421 @findex -a
1422 @findex -and
1423 And; @var{expr2} is not evaluated if @var{expr1} is false.
1425 @item @asis{@var{expr1} -o @var{expr2}}
1426 @itemx @asis{@var{expr1} -or @var{expr2}}
1427 @findex -o
1428 @findex -or
1429 Or; @var{expr2} is not evaluated if @var{expr1} is true.
1431 @item @asis{@var{expr1} , @var{expr2}}
1432 @findex ,
1433 List; both @var{expr1} and @var{expr2} are always evaluated.  True if
1434 @var{expr2} is true.  The value of @var{expr1} is discarded.  This
1435 operator lets you do multiple independent operations on one traversal,
1436 without depending on whether other operations succeeded.  The two
1437 operations @var{expr1} and @var{expr2} are not always fully
1438 independent, since @var{expr1} might have side effects like touching
1439 or deleting files, or it might use @samp{-prune} which would also
1440 affect @var{expr2}.
1441 @end table
1443 @code{find} searches the directory tree rooted at each file name by
1444 evaluating the expression from left to right, according to the rules
1445 of precedence, until the outcome is known (the left hand side is false
1446 for @samp{-and}, true for @samp{-or}), at which point @code{find}
1447 moves on to the next file name.
1449 There are two other tests that can be useful in complex expressions:
1451 @deffn Test -true
1452 Always true.
1453 @end deffn
1455 @deffn Test -false
1456 Always false.
1457 @end deffn
1459 @node Actions
1460 @chapter Actions
1462 There are several ways you can print information about the files that
1463 match the criteria you gave in the @code{find} expression.  You can
1464 print the information either to the standard output or to a file that
1465 you name.  You can also execute commands that have the file names as
1466 arguments.  You can use those commands as further filters to select
1467 files.
1469 @menu
1470 * Print File Name::
1471 * Print File Information::
1472 * Run Commands::
1473 * Delete Files::
1474 * Adding Tests::
1475 @end menu
1477 @node Print File Name
1478 @section Print File Name
1480 @deffn Action -print
1481 True; print the entire file name on the standard output, followed by a
1482 newline.  If there is the faintest possibility that one of the files
1483 for which you are searching might contain a newline, you should use
1484 @samp{-print0} instead.
1485 @end deffn
1487 @deffn Action -fprint file
1488 True; print the entire file name into file @var{file}, followed by a
1489 newline.  If @var{file} does not exist when @code{find} is run, it is
1490 created; if it does exist, it is truncated to 0 bytes.  The named
1491 output file is always created, even if no output is sent to it.  The
1492 file names @file{/dev/stdout} and @file{/dev/stderr} are handled
1493 specially; they refer to the standard output and standard error
1494 output, respectively.
1496 If there is the faintest possibility that one of the files for which
1497 you are searching might contain a newline, you should use
1498 @samp{-fprint0} instead.
1499 @end deffn
1502 @c @deffn Option -show-control-chars how
1503 @c This option affects how some of @code{find}'s actions treat
1504 @c unprintable characters in file names.  If @samp{how} is
1505 @c @samp{literal}, any subsequent actions (i.e., actions further on in the
1506 @c command line) print file names as-is.  
1507 @c 
1508 @c If this option is not specified, it currently defaults to @samp{safe}.
1509 @c If @samp{how} is @samp{safe}, C-like backslash escapes are used to
1510 @c indicate the non-printable characters for @samp{-ls} and @samp{-fls}.
1511 @c On the other hand, @samp{-print}, @samp{-fprint}, @samp{-fprintf} and
1512 @c @code{-printf} all quote unprintable characters if the data is going
1513 @c to a tty, and otherwise the data is emitted literally.
1514 @c 
1515 @c @table @code
1516 @c @item -ls
1517 @c Escaped if @samp{how} is @samp{safe}
1518 @c @item -fls
1519 @c Escaped if @samp{how} is @samp{safe}
1520 @c @item -print
1521 @c Always quoted if stdout is a tty,
1522 @c @samp{-show-control-chars} is ignored
1523 @c @item -print0
1524 @c Always literal, never escaped
1525 @c @item -fprint
1526 @c Always quoted if the destination is a tty;
1527 @c @samp{-show-control-chars} is ignored
1528 @c @item -fprint0
1529 @c Always literal, never escaped
1530 @c @item -fprintf
1531 @c If the destination is a tty, the @samp{%f}, 
1532 @c @samp{%F}, @samp{%h}, @samp{%l}, @samp{%p},
1533 @c and @samp{%P} directives produce quoted
1534 @c strings if stdout is a tty and are treated
1535 @c literally otherwise.
1536 @c @item -printf
1537 @c As for @code{-fprintf}.
1538 @c @end table
1539 @c @end deffn
1542 @node Print File Information
1543 @section Print File Information
1545 @deffn Action -ls
1546 True; list the current file in @samp{ls -dils} format on the standard
1547 output.  The output looks like this:
1549 @smallexample
1550 204744   17 -rw-r--r--   1 djm      staff       17337 Nov  2  1992 ./lwall-quotes
1551 @end smallexample
1553 The fields are:
1555 @enumerate
1556 @item
1557 The inode number of the file.  @xref{Hard Links}, for how to find
1558 files based on their inode number.
1560 @item
1561 the number of blocks in the file.  The block counts are of 1K blocks,
1562 unless the environment variable @code{POSIXLY_CORRECT} is set, in
1563 which case 512-byte blocks are used.  @xref{Size}, for how to find
1564 files based on their size.
1566 @item
1567 The file's type and file mode bits.  The type is shown as a dash for a
1568 regular file; for other file types, a letter like for @samp{-type} is
1569 used (@pxref{Type}).  The file mode bits are read, write, and execute/search for
1570 the file's owner, its group, and other users, respectively; a dash
1571 means the permission is not granted.  @xref{File Permissions}, for
1572 more details about file permissions.  @xref{Mode Bits}, for how to
1573 find files based on their file mode bits.
1575 @item
1576 The number of hard links to the file.
1578 @item
1579 The user who owns the file.
1581 @item
1582 The file's group.
1584 @item
1585 The file's size in bytes.
1587 @item
1588 The date the file was last modified.
1590 @item
1591 The file's name.  @samp{-ls} quotes non-printable characters in the
1592 file names using C-like backslash escapes.  This may change soon, as
1593 the treatment of unprintable characters is harmonised for @samp{-ls},
1594 @samp{-fls}, @samp{-print}, @samp{-fprint}, @samp{-printf} and
1595 @samp{-fprintf}.
1596 @end enumerate
1597 @end deffn
1599 @deffn Action -fls file
1600 True; like @samp{-ls} but write to @var{file} like @samp{-fprint}
1601 (@pxref{Print File Name}).  The named output file is always created,
1602 even if no output is sent to it.
1603 @end deffn
1605 @deffn Action -printf format
1606 True; print @var{format} on the standard output, interpreting @samp{\}
1607 escapes and @samp{%} directives.  Field widths and precisions can be
1608 specified as with the @code{printf} C function.  Format flags (like
1609 @samp{#} for example) may not work as you expect because many of the
1610 fields, even numeric ones, are printed with %s.  Numeric flags which
1611 are affected in this way include G, U, b, D, k and n.  This difference
1612 in behaviour means though that the format flag @samp{-} will work; it
1613 forces left-alignment of the field.  Unlike @samp{-print},
1614 @samp{-printf} does not add a newline at the end of the string.  If
1615 you want a newline at the end of the string, add a @samp{\n}.
1616 @end deffn
1618 @deffn Action -fprintf file format
1619 True; like @samp{-printf} but write to @var{file} like @samp{-fprint}
1620 (@pxref{Print File Name}).  The output file is always created, even if
1621 no output is ever sent to it.
1622 @end deffn
1624 @menu
1625 * Escapes::
1626 * Format Directives::
1627 * Time Formats::
1628 @end menu
1630 @node Escapes
1631 @subsection Escapes
1633 The escapes that @samp{-printf} and @samp{-fprintf} recognise are:
1635 @table @code
1636 @item \a
1637 Alarm bell.
1638 @item \b
1639 Backspace.
1640 @item \c
1641 Stop printing from this format immediately and flush the output.
1642 @item \f
1643 Form feed.
1644 @item \n
1645 Newline.
1646 @item \r
1647 Carriage return.
1648 @item \t
1649 Horizontal tab.
1650 @item \v
1651 Vertical tab.
1652 @item \\
1653 A literal backslash (@samp{\}).
1654 @item \0
1655 ASCII NUL.
1656 @item \NNN
1657 The character whose ASCII code is NNN (octal).
1658 @end table
1660 A @samp{\} character followed by any other character is treated as an
1661 ordinary character, so they both are printed, and a warning message is
1662 printed to the standard error output (because it was probably a typo).
1664 @node Format Directives
1665 @subsection Format Directives
1667 @samp{-printf} and @samp{-fprintf} support the following format
1668 directives to print information about the file being processed.  The C
1669 @code{printf} function, field width and precision specifiers are
1670 supported, as applied to string (%s) types. That is, you can specify
1671 "minimum field width"."maximum field width" for each directive.
1672 Format flags (like @samp{#} for example) may not work as you expect
1673 because many of the fields, even numeric ones, are printed with %s.
1674 The format flag @samp{-} does work; it forces left-alignment of the
1675 field.
1677 @samp{%%} is a literal percent sign.  A @samp{%} character followed by
1678 an unrecognised character (i.e., not a known directive or @code{printf}
1679 field width and precision specifier), is discarded (but the
1680 unrecognised character is printed), and a warning message is printed
1681 to the standard error output (because it was probably a typo).  Don't
1682 rely on this behaviour, because other directives may be added in the
1683 future.
1685 A @samp{%} at the end of the format argument causes undefined
1686 behaviour since there is no following character.  In some locales, it
1687 may hide your door keys, while in others it may remove the final page
1688 from the novel you are reading.
1690 @menu
1691 * Name Directives::
1692 * Ownership Directives::
1693 * Size Directives::
1694 * Location Directives::
1695 * Time Directives::
1696 * Formatting Flags::
1697 @end menu
1699 @node Name Directives
1700 @subsubsection Name Directives
1702 @table @code
1703 @item %p
1704 @c supports %-X.Yp
1705 File's name (not the absolute path name, but the name of the file as
1706 it was encountered by @code{find} - that is, as a relative path from
1707 one of the starting points).
1708 @item %f
1709 File's name with any leading directories removed (only the last
1710 element).
1711 @c supports %-X.Yf
1712 @item %h
1713 Leading directories of file's name (all but the last element and the
1714 slash before it).  If the file's name contains no slashes (for example
1715 because it was named on the command line and is in the current working
1716 directory), then ``%h'' expands to ``.''.  This prevents ``%h/%f''
1717 expanding to ``/foo'', which would be surprising and probably not
1718 desirable.
1719 @c supports %-X.Yh
1720 @item %P
1721 File's name with the name of the command line argument under which
1722 it was found removed from the beginning.
1723 @c supports %-X.YP
1724 @item %H
1725 Command line argument under which file was found.
1726 @c supports %-X.YH
1727 @end table
1729 @node Ownership Directives
1730 @subsubsection Ownership Directives
1732 @table @code
1733 @item %g
1734 @c supports %-X.Yg
1735 File's group name, or numeric group ID if the group has no name.
1736 @item %G
1737 @c supports %-X.Yg
1738 @c TODO: Needs to support # flag and 0 flag
1739 File's numeric group ID.
1740 @item %u
1741 @c supports %-X.Yu
1742 File's user name, or numeric user ID if the user has no name.
1743 @item %U
1744 @c supports %-X.Yu
1745 @c TODO: Needs to support # flag
1746 File's numeric user ID.
1747 @item %m
1748 @c full support, including # and 0.
1749 File's mode bits (in octal).  If you always want to have a leading
1750 zero on the number, use the '#' format flag, for example '%#m'.  
1752 The file mode bit numbers used are the traditional Unix
1753 numbers, which will be as expected on most systems, but if your
1754 system's file mode bit layout differs from the traditional Unix
1755 semantics, you will see a difference between the mode as printed by
1756 @samp{%m} and the mode as it appears in @code{struct stat}.
1758 @item %M
1759 File's type and mode bits (in symbolic form, as for @code{ls}).  This
1760 directive is supported in findutils 4.2.5 and later.
1761 @end table
1763 @node Size Directives
1764 @subsubsection Size Directives
1766 @table @code
1767 @item %k
1768 The amount of disk space used for this file in 1K blocks. Since disk
1769 space is allocated in multiples of the filesystem block size this is
1770 usually greater than %s/1024, but it can also be smaller if the file
1771 is a sparse file (that is, it has ``holes'').
1772 @item %b
1773 The amount of disk space used for this file in 512-byte blocks. Since
1774 disk space is allocated in multiples of the filesystem block size this
1775 is usually greater than %s/1024, but it can also be smaller if the
1776 file is a sparse file (that is, it has ``holes'').
1777 @item %s
1778 File's size in bytes.
1779 @item %S
1780 File's sparseness.  This is calculated as @code{(BLOCKSIZE*st_blocks /
1781 st_size)}.  The exact value you will get for an ordinary file of a
1782 certain length is system-dependent.  However, normally sparse files
1783 will have values less than 1.0, and files which use indirect blocks
1784 and have few holes may have a value which is greater than 1.0.  The
1785 value used for BLOCKSIZE is system-dependent, but is usually 512
1786 bytes.  If the file size is zero, the value printed is undefined.  On
1787 systems which lack support for st_blocks, a file's sparseness is
1788 assumed to be 1.0.
1789 @end table
1791 @node Location Directives
1792 @subsubsection Location Directives
1794 @table @code
1795 @item %d
1796 File's depth in the directory tree (depth below a file named on the
1797 command line, not depth below the root directory).  Files named on the
1798 command line have a depth of 0.  Subdirectories immediately below them
1799 have a depth of 1, and so on.
1800 @item %D
1801 The device number on which the file exists (the @code{st_dev} field of
1802 @code{struct stat}), in decimal.
1803 @item %F
1804 Type of the filesystem the file is on; this value can be used for
1805 @samp{-fstype} (@pxref{Directories}).
1806 @item %l
1807 Object of symbolic link (empty string if file is not a symbolic link).
1808 @item %i
1809 File's inode number (in decimal).
1810 @item %n
1811 Number of hard links to file.
1812 @item %y
1813 Type of the file as used with @samp{-type}.  If the file is a symbolic
1814 link, @samp{l} will be printed.
1815 @item %Y
1816 Type of the file as used with @samp{-type}.  If the file is a symbolic
1817 link, it is dereferenced.  If the file is a broken symbolic link,
1818 @samp{N} is printed.
1820 @end table
1822 @node Time Directives
1823 @subsubsection Time Directives
1825 Some of these directives use the C @code{ctime} function.  Its output
1826 depends on the current locale, but it typically looks like
1828 @example
1829 Wed Nov  2 00:42:36 1994
1830 @end example
1832 @table @code
1833 @item %a
1834 File's last access time in the format returned by the C @code{ctime}
1835 function.
1836 @item %A@var{k}
1837 File's last access time in the format specified by @var{k}
1838 (@pxref{Time Formats}).
1839 @item %c
1840 File's last status change time in the format returned by the C
1841 @code{ctime} function.
1842 @item %C@var{k}
1843 File's last status change time in the format specified by @var{k}
1844 (@pxref{Time Formats}).
1845 @item %t
1846 File's last modification time in the format returned by the C
1847 @code{ctime} function.
1848 @item %T@var{k}
1849 File's last modification time in the format specified by @var{k}
1850 (@pxref{Time Formats}).
1851 @end table
1853 @node Time Formats
1854 @subsection Time Formats
1856 Below are the formats for the directives @samp{%A}, @samp{%C}, and
1857 @samp{%T}, which print the file's timestamps.  Some of these formats
1858 might not be available on all systems, due to differences in the C
1859 @code{strftime} function between systems.
1861 @menu
1862 * Time Components::
1863 * Date Components::
1864 * Combined Time Formats::
1865 @end menu
1867 @node Time Components
1868 @subsubsection Time Components
1870 The following format directives print single components of the time.
1872 @table @code
1873 @item H
1874 hour (00..23)
1875 @item I
1876 hour (01..12)
1877 @item k
1878 hour ( 0..23)
1879 @item l
1880 hour ( 1..12)
1881 @item p
1882 locale's AM or PM
1883 @item Z
1884 time zone (e.g., EDT), or nothing if no time zone is determinable
1885 @item M
1886 minute (00..59)
1887 @item S
1888 second (00..61)
1889 @item @@
1890 seconds since Jan. 1, 1970, 00:00 GMT.
1891 @end table
1893 @node Date Components
1894 @subsubsection Date Components
1896 The following format directives print single components of the date.
1898 @table @code
1899 @item a
1900 locale's abbreviated weekday name (Sun..Sat)
1901 @item A
1902 locale's full weekday name, variable length (Sunday..Saturday)
1903 @item b
1904 @itemx h
1905 locale's abbreviated month name (Jan..Dec)
1906 @item B
1907 locale's full month name, variable length (January..December)
1908 @item m
1909 month (01..12)
1910 @item d
1911 day of month (01..31)
1912 @item w
1913 day of week (0..6)
1914 @item j
1915 day of year (001..366)
1916 @item U
1917 week number of year with Sunday as first day of week (00..53)
1918 @item W
1919 week number of year with Monday as first day of week (00..53)
1920 @item Y
1921 year (1970@dots{})
1922 @item y
1923 last two digits of year (00..99)
1924 @end table
1926 @node Combined Time Formats
1927 @subsubsection Combined Time Formats
1929 The following format directives print combinations of time and date
1930 components.
1932 @table @code
1933 @item r
1934 time, 12-hour (hh:mm:ss [AP]M)
1935 @item T
1936 time, 24-hour (hh:mm:ss)
1937 @item X
1938 locale's time representation (H:M:S)
1939 @item c
1940 locale's date and time (Sat Nov 04 12:02:33 EST 1989)
1941 @item D
1942 date (mm/dd/yy)
1943 @item x
1944 locale's date representation (mm/dd/yy)
1945 @item +
1946 Date and time, separated by '+', for example `2004-04-28+22:22:05'.
1947 The time is given in the current timezone (which may be affected by
1948 setting the TZ environment variable).  This is a GNU extension.
1949 @end table
1951 @node Formatting Flags
1952 @subsubsection Formatting Flags
1954 The @samp{%m} and @samp{%d} directives support the @samp{#}, @samp{0}
1955 and @samp{+} flags, but the other directives do not, even if they
1956 print numbers.  Numeric directives that do not support these flags
1957 include
1959 @samp{G},
1960 @samp{U},
1961 @samp{b},
1962 @samp{D},
1963 @samp{k} and
1964 @samp{n}.
1966 All fields support the format flag @samp{-}, which makes fields
1967 left-aligned.  That is, if the field width is greater than the actual
1968 contents of the field, the requisite number of spaces are printed
1969 after the field content instead of before it.
1971 @node Run Commands
1972 @section Run Commands
1974 You can use the list of file names created by @code{find} or
1975 @code{locate} as arguments to other commands.  In this way you can
1976 perform arbitrary actions on the files.
1978 @menu
1979 * Single File::
1980 * Multiple Files::
1981 * Querying::
1982 @end menu
1984 @node Single File
1985 @subsection Single File
1987 Here is how to run a command on one file at a time.
1989 @deffn Action -execdir command ;
1990 Execute @var{command}; true if zero status is returned.  @code{find}
1991 takes all arguments after @samp{-exec} to be part of the command until
1992 an argument consisting of @samp{;} is reached.  It replaces the string
1993 @samp{@{@}} by the current file name being processed everywhere it
1994 occurs in the command.  Both of these constructions need to be escaped
1995 (with a @samp{\}) or quoted to protect them from expansion by the
1996 shell.  The command is executed in the directory in which @code{find}
1997 was run.
1999 For example, to compare each C header file in or below the current
2000 directory with the file @file{/tmp/master}:
2002 @example
2003 find . -name '*.h' -execdir diff -u '@{@}' /tmp/master ';'
2004 @end example
2005 @end deffn
2007 If you use @samp{-execdir}, you must ensure that the current directory
2008 is not on @var{$PATH}, because otherwise an attacker could make
2009 @samp{find} run commands of their choice simply by leaving a
2010 suitably-named file in the right directory.  GNU find will refuse to
2011 run if you use @samp{-execdir} and the current directory is in
2012 @var{$PATH}.
2014 Another similar option, @samp{-exec} is supported, but is less secure.
2015 @xref{Security Considerations}, for a discussion of the security
2016 problems surrounding @samp{-exec}.
2019 @deffn Action -exec command ;
2020 This insecure variant of the @samp{-execdir} action is specified by
2021 POSIX.  The main difference is that the command is executed in the
2022 directory from which @code{find} was invoked, meaning that @samp{@{@}}
2023 is expanded to a relative path starting with the name of one of the
2024 starting directories, rather than just the basename of the matched
2025 file.
2027 While some implementations of @code{find} replace the @samp{@{@}} only
2028 where it appears on its own in an argument, GNU @code{find} replaces
2029 @samp{@{@}} wherever it appears.
2030 @end deffn
2033 @node Multiple Files
2034 @subsection Multiple Files
2036 Sometimes you need to process files one at a time.  But usually this
2037 is not necessary, and, it is faster to run a command on as many files
2038 as possible at a time, rather than once per file.  Doing this saves on
2039 the time it takes to start up the command each time.
2041 The @samp{-execdir} and @samp{-exec} actions have variants that build
2042 command lines containing as many matched files as possible.
2044 @deffn Action -execdir command @{@} +
2045 This works as for @samp{-execdir command ;}, except that the
2046 @samp{@{@}} at the end of the command is expanded to a list of names
2047 of matching files.  This expansion is done in such a way as to avoid
2048 exceeding the maximum command line length available on the system.
2049 Only one @samp{@{@}} is allowed within the command, and it must appear
2050 at the end, immediately before the @samp{+}.  A @samp{+} appearing in
2051 any position other than immediately after @samp{@{@}} is not
2052 considered to be special (that is, it does not terminate the command).
2053 @end deffn
2056 @deffn Action -exec command @{@} +
2057 This insecure variant of the @samp{-execdir} action is specified by
2058 POSIX.  The main difference is that the command is executed in the
2059 directory from which @code{find} was invoked, meaning that @samp{@{@}}
2060 is expanded to a relative path starting with the name of one of the
2061 starting directories, rather than just the basename of the matched
2062 file.
2063 @end deffn
2065 Before @code{find} exits, any partially-built command lines are
2066 executed.  This happens even if the exit was caused by the
2067 @samp{-quit} action.  However, some types of error (for example not
2068 being able to invoke @code{stat()} on the current directory) can cause
2069 an immediate fatal exit.  In this situation, any partially-built
2070 command lines will not be invoked (this prevents possible infinite
2071 loops).
2073 At first sight, it looks like the list of filenames to be processed
2074 can only be at the end of the command line, and that this might be a
2075 problem for some comamnds (@code{cp} and @code{rsync} for example).
2077 However, there is a slightly obscure but powerful workarouund for this
2078 problem which takes advantage of the behaviour of @code{sh -c}:-
2080 @example
2081 find startpoint -tests @dots{} -exec sh -c 'scp "$@@" remote:/dest' sh @{@} + 
2082 @end example
2084 In the example above, the filenames we want to work on need to occur
2085 on the @code{scp} command line before the name of the destination.  We
2086 use the shell to invoke the command @code{scp "$@@" remote:/dest} and
2087 the shell expands @code{"$@@"} to the list of filenames we want to
2088 process.
2090 Another, but less secure, way to run a command on more than one file
2091 at once, is to use the @code{xargs} command, which is invoked like
2092 this:
2094 @example
2095 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
2096 @end example
2098 @code{xargs} normally reads arguments from the standard input.  These
2099 arguments are delimited by blanks (which can be protected with double
2100 or single quotes or a backslash) or newlines.  It executes the
2101 @var{command} (default is @file{/bin/echo}) one or more times with any
2102 @var{initial-arguments} followed by arguments read from standard
2103 input.  Blank lines on the standard input are ignored.  If the
2104 @samp{-L} option is in use, trailing blanks indicate that @code{xargs}
2105 should consider the following line to be part of this one.
2107 Instead of blank-delimited names, it is safer to use @samp{find
2108 -print0} or @samp{find -fprint0} and process the output by giving the
2109 @samp{-0} or @samp{--null} option to GNU @code{xargs}, GNU @code{tar},
2110 GNU @code{cpio}, or @code{perl}.  The @code{locate} command also has a
2111 @samp{-0} or @samp{--null} option which does the same thing.
2113 You can use shell command substitution (backquotes) to process a list
2114 of arguments, like this:
2116 @example
2117 grep -l sprintf `find $HOME -name '*.c' -print`
2118 @end example
2120 However, that method produces an error if the length of the @samp{.c}
2121 file names exceeds the operating system's command line length limit.
2122 @code{xargs} avoids that problem by running the command as many times
2123 as necessary without exceeding the limit:
2125 @example
2126 find $HOME -name '*.c' -print | xargs grep -l sprintf
2127 @end example
2129 However, if the command needs to have its standard input be a terminal
2130 (@code{less}, for example), you have to use the shell command
2131 substitution method or use the @samp{--arg-file} option of
2132 @code{xargs}.
2134 The @code{xargs} command will process all its input, building command
2135 lines and executing them, unless one of the commands exits with a
2136 status of 255 (this will cause xargs to issue an error message and
2137 stop) or it reads a line contains the end of file string specified
2138 with the @samp{--eof} option.
2140 @menu
2141 * Unsafe File Name Handling::
2142 * Safe File Name Handling::
2143 * Unusual Characters in File Names::
2144 * Limiting Command Size::
2145 * Interspersing File Names::
2146 @end menu
2148 @node Unsafe File Name Handling
2149 @subsubsection Unsafe File Name Handling
2151 Because file names can contain quotes, backslashes, blank characters,
2152 and even newlines, it is not safe to process them using @code{xargs}
2153 in its default mode of operation.  But since most files' names do not
2154 contain blanks, this problem occurs only infrequently.  If you are
2155 only searching through files that you know have safe names, then you
2156 need not be concerned about it.
2158 Error messages issued by @code{find} and @code{locate} quote unusual
2159 characters in file names in order to prevent unwanted changes in the
2160 terminal's state.
2163 @c This example is adapted from:
2164 @c From: pfalstad@stone.Princeton.EDU (Paul John Falstad)
2165 @c Newsgroups: comp.unix.shell
2166 @c Subject: Re: Beware xargs security holes
2167 @c Date: 16 Oct 90 19:12:06 GMT
2169 In many applications, if @code{xargs} botches processing a file
2170 because its name contains special characters, some data might be lost.
2171 The importance of this problem depends on the importance of the data
2172 and whether anyone notices the loss soon enough to correct it.
2173 However, here is an extreme example of the problems that using
2174 blank-delimited names can cause.  If the following command is run
2175 daily from @code{cron}, then any user can remove any file on the
2176 system:
2178 @example
2179 find / -name '#*' -atime +7 -print | xargs rm
2180 @end example
2182 For example, you could do something like this:
2184 @example
2185 eg$ echo > '#
2186 vmunix'
2187 @end example
2189 @noindent
2190 and then @code{cron} would delete @file{/vmunix}, if it ran
2191 @code{xargs} with @file{/} as its current directory.
2193 To delete other files, for example @file{/u/joeuser/.plan}, you could
2194 do this:
2196 @example
2197 eg$ mkdir '#
2199 eg$ cd '#
2201 eg$ mkdir u u/joeuser u/joeuser/.plan'
2203 eg$ echo > u/joeuser/.plan'
2204 /#foo'
2205 eg$ cd ..
2206 eg$ find . -name '#*' -print | xargs echo
2207 ./# ./# /u/joeuser/.plan /#foo
2208 @end example
2210 @node Safe File Name Handling
2211 @subsubsection Safe File Name Handling
2213 Here is how to make @code{find} output file names so that they can be
2214 used by other programs without being mangled or misinterpreted.  You
2215 can process file names generated this way by giving the @samp{-0} or
2216 @samp{--null} option to GNU @code{xargs}, GNU @code{tar}, GNU
2217 @code{cpio}, or @code{perl}.
2219 @deffn Action -print0
2220 True; print the entire file name on the standard output, followed by a
2221 null character.
2222 @end deffn
2224 @deffn Action -fprint0 file
2225 True; like @samp{-print0} but write to @var{file} like @samp{-fprint}
2226 (@pxref{Print File Name}).  The output file is always created.
2227 @end deffn
2229 As of findutils version 4.2.4, the @code{locate} program also has a
2230 @samp{--null} option which does the same thing.  For similarity with
2231 @code{xargs}, the short form of the option @samp{-0} can also be used.
2233 If you want to be able to handle file names safely but need to run
2234 commands which want to be connected to a terminal on their input, you
2235 can use the @samp{--arg-file} option to @code{xargs} like this:
2237 @example
2238 find / -name xyzzy -print0 > list
2239 xargs --null --arg-file=list munge
2240 @end example
2242 The example above runs the @code{munge} program on all the files named
2243 @file{xyzzy} that we can find, but @code{munge}'s input will still be
2244 the terminal (or whatever the shell was using as standard input).  If
2245 your shell has the ``process substitution'' feature @samp{<(...)}, you
2246 can do this in just one step:
2248 @example
2249 xargs --null --arg-file=<(find / -name xyzzy -print0) munge
2250 @end example
2252 @node Unusual Characters in File Names
2253 @subsubsection Unusual Characters in File Names
2254 As discussed above, you often need to be careful about how the names
2255 of files are handled by @code{find} and other programs.  If the output
2256 of @code{find} is not going to another program but instead is being
2257 shown on a terminal, this can still be a problem.  For example, some
2258 character sequences can reprogram the function keys on some terminals.
2259 @xref{Security Considerations}, for a discussion of other security
2260 problems relating to @code{find}.
2262 Unusual characters are handled differently by various
2263 actions, as described below.
2265 @table @samp
2266 @item -print0
2267 @itemx -fprint0
2268 Always print the exact file name, unchanged, even if the output is
2269 going to a terminal.
2270 @item -ok
2271 @itemx -okdir
2272 Always print the exact file name, unchanged.  This will probably
2273 change in a future release.
2274 @item -ls
2275 @itemx -fls
2276 Unusual characters are always escaped.  White space, backslash, and
2277 double quote characters are printed using C-style escaping (for
2278 example @samp{\f}, @samp{\"}).  Other unusual characters are printed
2279 using an octal escape.  Other printable characters (for @samp{-ls} and
2280 @samp{-fls} these are the characters between octal 041 and 0176) are
2281 printed as-is.
2282 @item -printf
2283 @itemx -fprintf
2284 If the output is not going to a terminal, it is printed as-is.
2285 Otherwise, the result depends on which directive is in use:
2287 @table @asis
2288 @item %D, %F, %H, %Y, %y
2289 These expand to values which are not under control of files' owners,
2290 and so are printed as-is.
2291 @item  %a, %b, %c, %d, %g, %G, %i, %k, %m, %M, %n, %s, %t, %u, %U
2292 These have values which are under the control of files' owners but
2293 which cannot be used to send arbitrary data to the terminal, and so
2294 these are printed as-is.
2295 @item %f, %h, %l, %p, %P
2296 The output of these directives is quoted if the output is going to a
2297 terminal.
2299 This quoting is performed in the same way as for GNU @code{ls}.  This
2300 is not the same quoting mechanism as the one used for @samp{-ls} and
2301 @samp{fls}.  If you are able to decide what format to use for the
2302 output of @code{find} then it is normally better to use @samp{\0} as a
2303 terminator than to use newline, as file names can contain white space
2304 and newline characters.
2305 @end table
2306 @item -print
2307 @itemx -fprint
2308 Quoting is handled in the same way as for the @samp{%p} directive of
2309 @samp{-printf} and @samp{-fprintf}.  If you are using @code{find} in a
2310 script or in a situation where the matched files might have arbitrary
2311 names, you should consider using @samp{-print0} instead of
2312 @samp{-print}.
2313 @end table
2316 The @code{locate} program quotes and escapes unusual characters in
2317 file names in the same way as @code{find}'s @samp{-print} action.
2319 The behaviours described above may change soon, as the treatment of
2320 unprintable characters is harmonised for @samp{-ls}, @samp{-fls},
2321 @samp{-print}, @samp{-fprint}, @samp{-printf} and @samp{-fprintf}.
2323 @node Limiting Command Size
2324 @subsubsection Limiting Command Size
2326 @code{xargs} gives you control over how many arguments it passes to
2327 the command each time it executes it.  By default, it uses up to
2328 @code{ARG_MAX} - 2k, or 128k, whichever is smaller, characters per
2329 command.  It uses as many lines and arguments as fit within that
2330 limit.  The following options modify those values.
2332 @table @code
2333 @item --no-run-if-empty
2334 @itemx -r
2335 If the standard input does not contain any nonblanks, do not run the
2336 command.  By default, the command is run once even if there is no
2337 input.  This option is a GNU extension.
2339 @item --max-lines@r{[}=@var{max-lines}@r{]}
2340 @itemx -L @var{max-lines}
2341 @itemx -l@r{[}@var{max-lines}@r{]}
2342 Use at most @var{max-lines} nonblank input lines per command line;
2343 @var{max-lines} defaults to 1 if omitted; omitting the argument is not
2344 allowed in the case of the @samp{-L} option.  Trailing blanks cause an
2345 input line to be logically continued on the next input line, for the
2346 purpose of counting the lines.  Implies @samp{-x}.  The preferred name
2347 for this option is @samp{-L} as this is specified by POSIX.  
2349 @item --max-args=@var{max-args}
2350 @itemx -n @var{max-args}
2351 Use at most @var{max-args} arguments per command line.  Fewer than
2352 @var{max-args} arguments will be used if the size (see the @samp{-s}
2353 option) is exceeded, unless the @samp{-x} option is given, in which
2354 case @code{xargs} will exit.
2356 @item --max-chars=@var{max-chars}
2357 @itemx -s @var{max-chars}
2358 Use at most @var{max-chars} characters per command line, including the
2359 command initial arguments and the terminating nulls at the ends of the
2360 argument strings.  If you specify a value for this option which is too
2361 large or small, a warning message is printed and the appropriate upper
2362 or lower limit is used instead.  You can use @samp{--show-limits}
2363 option to understand the command-line limits applying to @code{xargs}
2364 and how this is affected by any other options.  The POSIX limits shown
2365 when you do this have already been adjusted to take into account the
2366 size of your environment variables.  
2368 The largest allowed value is system-dependent, and is calculated as
2369 the argument length limit for exec, less the size of your environment,
2370 less 2048 bytes of headroom.  If this value is more than 128KiB,
2371 128Kib is used as the default value; otherwise, the default value is
2372 the maximum.
2375 @item --max-procs=@var{max-procs}
2376 @itemx -P @var{max-procs}
2377 Run up to @var{max-procs} processes at a time; the default is 1.  If
2378 @var{max-procs} is 0, @code{xargs} will run as many processes as
2379 possible at a time.  Use the @samp{-n}, @samp{-s}, or @samp{-L} option
2380 with @samp{-P}; otherwise chances are that the command will be run
2381 only once.
2382 @end table
2384 @node Interspersing File Names
2385 @subsubsection Interspersing File Names
2387 @code{xargs} can insert the name of the file it is processing between
2388 arguments you give for the command.  Unless you also give options to
2389 limit the command size (@pxref{Limiting Command Size}), this mode of
2390 operation is equivalent to @samp{find -exec} (@pxref{Single File}).
2392 @table @code
2393 @item --replace@r{[}=@var{replace-str}@r{]}
2394 @itemx -I @var{replace-str}
2395 @itemx -i @var{replace-str}
2396 Replace occurrences of @var{replace-str} in the initial arguments with
2397 names read from the input.  Also, unquoted blanks do not terminate
2398 arguments; instead, the input is split at newlines only.  For the
2399 @samp{-i} option, if @var{replace-str} is omitted for @samp{--replace}
2400 or @samp{-i}, it defaults to @samp{@{@}} (like for @samp{find -exec}).
2401 Implies @samp{-x} and @samp{-l 1}.  @samp{-i} is deprecated in favour
2402 of @samp{-I}. As an example, to sort each file in the @file{bills}
2403 directory, leaving the output in that file name with @file{.sorted}
2404 appended, you could do:
2406 @example
2407 find bills -type f | xargs -I XX sort -o XX.sorted XX
2408 @end example
2410 @noindent
2411 The equivalent command using @samp{find -execdir} is:
2413 @example
2414 find bills -type f -execdir sort -o '@{@}.sorted' '@{@}' ';'
2415 @end example
2416 @end table
2419 When you use the @samp{-I} option, each line read from the input is
2420 buffered internally.  This means that there is an upper limit on the
2421 length of input line that xargs will accept when used with the
2422 @samp{-I} option.  To work around this limitation, you can use the
2423 @samp{-s} option to increase the amount of buffer space that xargs
2424 uses, and you can also use an extra invocation of xargs to ensure that
2425 very long lines do not occur.  For example:
2427 @example
2428 somecommand | xargs -s 50000 echo | xargs -I '@{@}' -s 100000 rm '@{@}'
2429 @end example
2431 Here, the first invocation of @code{xargs} has no input line length
2432 limit because it doesn't use the @samp{-I} option. The second
2433 invocation of @code{xargs} does have such a limit, but we have ensured
2434 that the it never encounters a line which is longer than it can
2435 handle.  
2437 This is not an ideal solution.  Instead, the @samp{-I} option should
2438 not impose a line length limit (apart from any limit imposed by the
2439 operating system) and so one might consider this limitation to be a
2440 bug.  A better solution would be to allow @code{xargs -I} to
2441 automatically move to a larger value for the @samp{-s} option when
2442 this is needed.
2444 This sort of problem doesn't occur with the output of @code{find}
2445 because it emits just one filename per line.
2447 @node Querying
2448 @subsection Querying
2450 To ask the user whether to execute a command on a single file, you can
2451 use the @code{find} primary @samp{-okdir} instead of @samp{-execdir},
2452 and the @code{find} primary @samp{-ok} instead of @samp{-exec}:
2454 @deffn Action -okdir command ;
2455 Like @samp{-execdir} (@pxref{Single File}), but ask the user first (on
2456 the standard input); if the response does not start with @samp{y} or
2457 @samp{Y}, do not run the command, and return false.  If the command is
2458 run, its standard input is redirected from @file{/dev/null}.
2459 @end deffn
2461 @deffn Action -ok command ;
2462 This insecure variant of the @samp{-okdir} action is specified by
2463 POSIX.  The main difference is that the command is executed in the
2464 directory from which @code{find} was invoked, meaning that @samp{@{@}}
2465 is expanded to a relative path starting with the name of one of the
2466 starting directories, rather than just the basename of the matched
2467 file.  If the command is run, its standard input is redirected from
2468 @file{/dev/null}.
2469 @end deffn
2471 When processing multiple files with a single command, to query the
2472 user you give @code{xargs} the following option.  When using this
2473 option, you might find it useful to control the number of files
2474 processed per invocation of the command (@pxref{Limiting Command
2475 Size}).
2477 @table @code
2478 @item --interactive
2479 @itemx -p
2480 Prompt the user about whether to run each command line and read a line
2481 from the terminal.  Only run the command line if the response starts
2482 with @samp{y} or @samp{Y}.  Implies @samp{-t}.
2483 @end table
2485 @node Delete Files
2486 @section Delete Files
2488 @deffn Action -delete
2489 Delete files or directories; true if removal succeeded.  If the
2490 removal failed, an error message is issued.
2492 The use of the @samp{-delete} action on the command line automatically
2493 turns on the @samp{-depth} option (@pxref{find Expressions}).
2494 @end deffn
2496 @node Adding Tests
2497 @section Adding Tests
2499 You can test for file attributes that none of the @code{find} builtin
2500 tests check.  To do this, use @code{xargs} to run a program that
2501 filters a list of files printed by @code{find}.  If possible, use
2502 @code{find} builtin tests to pare down the list, so the program run by
2503 @code{xargs} has less work to do.  The tests builtin to @code{find}
2504 will likely run faster than tests that other programs perform.
2506 For reasons of efficiency it is often useful to limit the number of
2507 times an external program has to be run.  For this reason, it is often
2508 a good idea to implement ``extended'' tests by using @code{xargs}.
2510 For example, here is a way to print the names of all of the unstripped
2511 binaries in the @file{/usr/local} directory tree.  Builtin tests avoid
2512 running @code{file} on files that are not regular files or are not
2513 executable.
2515 @example
2516 find /usr/local -type f -perm /a=x | xargs file |
2517   grep 'not stripped' | cut -d: -f1
2518 @end example
2520 @noindent
2521 The @code{cut} program removes everything after the file name from the
2522 output of @code{file}.
2524 However, using @code{xargs} can present important security problems
2525 (@pxref{Security Considerations}).  These can be avoided by using
2526 @samp{-execdir}.  The @samp{-execdir} action is also a useful way of
2527 putting your own test in the middle of a set of other tests or actions
2528 for @code{find} (for example, you might want to use @samp{-prune}).
2530 @c Idea from Martin Weitzel.
2531 To place a special test somewhere in the middle of a @code{find}
2532 expression, you can use @samp{-execdir} (or, less securely,
2533 @samp{-exec}) to run a program that performs the test.  Because
2534 @samp{-execdir} evaluates to the exit status of the executed program,
2535 you can use a program (which can be a shell script) that tests for a
2536 special attribute and make it exit with a true (zero) or false
2537 (non-zero) status.  It is a good idea to place such a special test
2538 @emph{after} the builtin tests, because it starts a new process which
2539 could be avoided if a builtin test evaluates to false.
2541 Here is a shell script called @code{unstripped} that checks whether
2542 its argument is an unstripped binary file:
2544 @example
2545 #! /bin/sh
2546 file "$1" | grep -q "not stripped"
2547 @end example
2550 This script relies on the shell exiting with the status of
2551 the last command in the pipeline, in this case @code{grep}.  The
2552 @code{grep} command exits with a true status if it found any matches,
2553 false if not.  Here is an example of using the script (assuming it is
2554 in your search path).  It lists the stripped executables (and shell
2555 scripts) in the file @file{sbins} and the unstripped ones in
2556 @file{ubins}.
2558 @example
2559 find /usr/local -type f -perm /a=x \
2560   \( -execdir unstripped '@{@}' \; -fprint ubins -o -fprint sbins \)
2561 @end example
2564 @node Databases
2565 @chapter File Name Databases
2567 The file name databases used by @code{locate} contain lists of files
2568 that were in particular directory trees when the databases were last
2569 updated.  The file name of the default database is determined when
2570 @code{locate} and @code{updatedb} are configured and installed.  The
2571 frequency with which the databases are updated and the directories for
2572 which they contain entries depend on how often @code{updatedb} is run,
2573 and with which arguments.
2575 You can obtain some statistics about the databases by using
2576 @samp{locate --statistics}.
2578 @menu
2579 * Database Locations::
2580 * Database Formats::
2581 * Newline Handling::
2582 @end menu
2585 @node Database Locations
2586 @section Database Locations
2588 There can be multiple file name databases.  Users can select which
2589 databases @code{locate} searches using the @code{LOCATE_PATH}
2590 environment variable or a command line option.  The system
2591 administrator can choose the file name of the default database, the
2592 frequency with which the databases are updated, and the directories
2593 for which they contain entries.  File name databases are updated by
2594 running the @code{updatedb} program, typically nightly.
2596 In networked environments, it often makes sense to build a database at
2597 the root of each filesystem, containing the entries for that
2598 filesystem.  @code{updatedb} is then run for each filesystem on the
2599 fileserver where that filesystem is on a local disk, to prevent
2600 thrashing the network.
2602 @xref{Invoking updatedb}, for the description of the options to
2603 @code{updatedb}.  These options can be used to specify which
2604 directories are indexed by each database file.
2606 The default location for the locate database depends on how findutils
2607 is built, but the findutils installation accompanying this manual uses
2608 the default location @file{@value{LOCATE_DB}}.
2610 If no database exists at @file{@value{LOCATE_DB}} but the user did not
2611 specify where to look (by using @samp{-d} or setting
2612 @code{LOCATE_PATH}), then @code{locate} will also check for a
2613 ``secure'' database in @file{/var/lib/slocate/slocate.db}.
2615 @node Database Formats
2616 @section Database Formats
2618 The file name databases contain lists of files that were in particular
2619 directory trees when the databases were last updated.  The file name
2620 database format changed starting with GNU @code{locate} version 4.0 to
2621 allow machines with different byte orderings to share the databases.
2623 GNU @code{locate} can read both the old and new database formats.
2624 However, old versions of @code{locate} (on other Unix systems, or GNU
2625 @code{locate} before version 4.0) produce incorrect results if run
2626 against a database in something other than the old format.
2628 Support for the old database format will eventually be discontinued,
2629 first in @code{updatedb} and later in @code{locate}.
2631 If you run @samp{locate --statistics}, the resulting summary indicates
2632 the type of each @code{locate} database.   You select which database
2633 format @code{updatedb} will use with the @samp{--dbformat} option.
2636 @menu
2637 * LOCATE02 Database Format::
2638 * Sample LOCATE02 Database::
2639 * slocate Database Format::
2640 * Old Database Format::
2641 @end menu
2643 @node LOCATE02 Database Format
2644 @subsection LOCATE02 Database Format
2646 @code{updatedb} runs a program called @code{frcode} to
2647 @dfn{front-compress} the list of file names, which reduces the
2648 database size by a factor of 4 to 5.  Front-compression (also known as
2649 incremental encoding) works as follows.
2651 The database entries are a sorted list (case-insensitively, for users'
2652 convenience).  Since the list is sorted, each entry is likely to share
2653 a prefix (initial string) with the previous entry.  Each database
2654 entry begins with an offset-differential count byte, which is the
2655 additional number of characters of prefix of the preceding entry to
2656 use beyond the number that the preceding entry is using of its
2657 predecessor.  (The counts can be negative.)  Following the count is a
2658 null-terminated ASCII remainder---the part of the name that follows
2659 the shared prefix.
2661 If the offset-differential count is larger than can be stored in a
2662 byte (+/-127), the byte has the value 0x80 and the count follows in a
2663 2-byte word, with the high byte first (network byte order).
2665 Every database begins with a dummy entry for a file called
2666 @file{LOCATE02}, which @code{locate} checks for to ensure that the
2667 database file has the correct format; it ignores the entry in doing
2668 the search.
2670 Databases cannot be concatenated together, even if the first (dummy)
2671 entry is trimmed from all but the first database.  This is because the
2672 offset-differential count in the first entry of the second and
2673 following databases will be wrong.
2675 In the output of @samp{locate --statistics}, the new database format
2676 is referred to as @samp{LOCATE02}.
2678 @node Sample LOCATE02 Database
2679 @subsection Sample LOCATE02 Database
2681 Sample input to @code{frcode}:
2682 @c with nulls changed to newlines:
2684 @example
2685 /usr/src
2686 /usr/src/cmd/aardvark.c
2687 /usr/src/cmd/armadillo.c
2688 /usr/tmp/zoo
2689 @end example
2691 Length of the longest prefix of the preceding entry to share:
2693 @example
2694 0 /usr/src
2695 8 /cmd/aardvark.c
2696 14 rmadillo.c
2697 5 tmp/zoo
2698 @end example
2700 Output from @code{frcode}, with trailing nulls changed to newlines
2701 and count bytes made printable:
2703 @example
2704 0 LOCATE02
2705 0 /usr/src
2706 8 /cmd/aardvark.c
2707 6 rmadillo.c
2708 -9 tmp/zoo
2709 @end example
2711 (6 = 14 - 8, and -9 = 5 - 14)
2713 @node slocate Database Format
2714 @subsection slocate Database Format
2716 The @code{slocate} program uses a database format similar to, but not
2717 quite the same as, GNU @code{locate}.  The first byte of the database
2718 specifies its @dfn{security level}.  If the security level is 0,
2719 @code{slocate} will read, match and print filenames on the basis of
2720 the information in the database only.  However, if the security level
2721 byte is 1, @code{slocate} omits entries from its output if the
2722 invoking user is unable to access them.  The second byte of the
2723 database is zero.  The second byte is immediately followed by the
2724 first database entry.  The first entry in the database is not preceded
2725 by any differential count or dummy entry.  Instead the differential
2726 count for the first item is assumed to be zero.
2728 Starting with the second entry (if any) in the database, data is
2729 interpreted as for the GNU LOCATE02 format.
2731 @node Old Database Format
2732 @subsection Old Database Format
2734 The old database format is used by Unix @code{locate} and @code{find}
2735 programs and earlier releases of the GNU ones.  @code{updatedb}
2736 produces this format if given the @samp{--old-format} option.
2738 @code{updatedb} runs programs called @code{bigram} and @code{code} to
2739 produce old-format databases.  The old format differs from the new one
2740 in the following ways.  Instead of each entry starting with an
2741 offset-differential count byte and ending with a null, byte values
2742 from 0 through 28 indicate offset-differential counts from -14 through
2743 14.  The byte value indicating that a long offset-differential count
2744 follows is 0x1e (30), not 0x80.  The long counts are stored in host
2745 byte order, which is not necessarily network byte order, and host
2746 integer word size, which is usually 4 bytes.  They also represent a
2747 count 14 less than their value.  The database lines have no
2748 termination byte; the start of the next line is indicated by its first
2749 byte having a value <= 30.
2751 In addition, instead of starting with a dummy entry, the old database
2752 format starts with a 256 byte table containing the 128 most common
2753 bigrams in the file list.  A bigram is a pair of adjacent bytes.
2754 Bytes in the database that have the high bit set are indexes (with the
2755 high bit cleared) into the bigram table.  The bigram and
2756 offset-differential count coding makes these databases 20-25% smaller
2757 than the new format, but makes them not 8-bit clean.  Any byte in a
2758 file name that is in the ranges used for the special codes is replaced
2759 in the database by a question mark, which not coincidentally is the
2760 shell wildcard to match a single character.
2762 The old format therefore cannot faithfully store entries with
2763 non-ASCII characters. It therefore should not be used in
2764 internationalised environments.
2766 The output of @samp{locate --statistics} will give an incorrect count
2767 of the number of file names containing newlines or high-bit characters
2768 for old-format databases.
2770 @node Newline Handling
2771 @section Newline Handling
2773 Within the database, file names are terminated with a null character.
2774 This is the case for both the old and the new format.
2776 When the new database format is being used, the compression technique
2777 used to generate the database though relies on the ability to sort the
2778 list of files before they are presented to @code{frcode}.
2780 If the system's sort command allows its input list of files to be
2781 separated with null characters via the @samp{-z} option, this option
2782 is used and therefore @code{updatedb} and @code{locate} will both
2783 correctly handle file names containing newlines.  If the @code{sort}
2784 command lacks support for this, the list of files is delimited with
2785 the newline character, meaning that parts of file names containing
2786 newlines will be incorrectly sorted.  This can result in both
2787 incorrect matches and incorrect failures to match.
2789 On the other hand, if you are using the old database format, file
2790 names with embedded newlines are not correctly handled.  There is no
2791 technical limitation which enforces this, it's just that the
2792 @code{bigram} program has not been updated to support lists of file
2793 names separated by nulls.
2795 So, if you are using the new database format (this is the default) and
2796 your system uses GNU @code{sort}, newlines will be correctly handled
2797 at all times.  Otherwise, newlines may not be correctly handled.
2799 @node File Permissions
2800 @chapter File Permissions
2802 @include perm.texi
2804 @include getdate.texi
2806 @node Reference
2807 @chapter Reference
2809 Below are summaries of the command line syntax for the programs
2810 discussed in this manual.
2812 @menu
2813 * Invoking find::
2814 * Invoking locate::
2815 * Invoking updatedb::
2816 * Invoking xargs::
2817 * Regular Expressions::
2818 * Environment Variables::
2819 @end menu
2821 @node Invoking find
2822 @section Invoking @code{find}
2824 @example
2825 find @r{[-H] [-L] [-P] [-D @var{debugoptions}] [-O@var{level}]} @r{[}@var{file}@dots{}@r{]} @r{[}@var{expression}@r{]}
2826 @end example
2828 @code{find} searches the directory tree rooted at each file name
2829 @var{file} by evaluating the @var{expression} on each file it finds in
2830 the tree.
2832 The command line may begin with the @samp{-H}, @samp{-L}, @samp{-P},
2833 @samp{-D} and @samp{-O} options.  These are followed by a list of
2834 files or directories that should be searched.  If no files to search
2835 are specified, the current directory (@file{.}) is used.
2837 This list of files to search is followed by a list of expressions
2838 describing the files we wish to search for.  The first part of the
2839 expression is recognised by the fact that it begins with @samp{-}
2840 followed by some other letters (for example @samp{-print}), or is
2841 either @samp{(} or @samp{!}.  Any arguments after it are the rest of
2842 the expression.  
2844 If no expression is given, the expression @samp{-print} is used.
2846 The @code{find} command exits with status zero if all files matched
2847 are processed successfully, greater than zero if errors occur.
2849 The @code{find} program also recognises two options for administrative
2850 use:
2852 @table @samp
2853 @item --help
2854 Print a summary of the command line usage and exit.
2855 @item --version
2856 Print the version number of @code{find} and exit.
2857 @end table
2859 The @samp{-version} option is a synonym for @samp{--version}
2862 @menu
2863 * Filesystem Traversal Options::
2864 * Warning Messages::
2865 * Optimisation Options::
2866 * Debug Options::
2867 * Find Expressions::
2868 @end menu
2870 @node Filesystem Traversal Options
2871 @subsection Filesystem Traversal Options
2873 The options @samp{-H}, @samp{-L} or @samp{-P} may be specified at the
2874 start of the command line (if none of these is specified, @samp{-P} is
2875 assumed).  If you specify more than one of these options, the last one
2876 specified takes effect (but note that the @samp{-follow} option is
2877 equivalent to @samp{-L}).  
2879 @table @code
2880 @item -P
2881 Never follow symbolic links (this is the default), except in the case
2882 of the @samp{-xtype} predicate.
2883 @item -L
2884 Always follow symbolic links, except in the case of the @samp{-xtype}
2885 predicate.
2886 @item -H
2887 Follow symbolic links specified in the list of files to search, or
2888 which are otherwise specified on the command line.
2889 @end table
2891 If @code{find} would follow a symbolic link, but cannot for any reason
2892 (for example, because it has insufficient permissions or the link is
2893 broken), it falls back on using the properties of the symbolic link
2894 itself.  @ref{Symbolic Links} for a more complete description of how
2895 symbolic links are handled.
2897 @node Warning Messages
2898 @subsection Warning Messages
2900 If there is an error on the @code{find} command line, an error message
2901 is normally issued.  However, there are some usages that are
2902 inadvisable but which @code{find} should still accept.  Under these
2903 circumstances, @code{find} may issue a warning message.  By default,
2904 warnings are enabled only if @code{find} is being run interactively
2905 (specifically, if the standard input is a terminal).  Warning messages
2906 can be controlled explicitly by the use of options on the command
2907 line:
2909 @table @code
2910 @item -warn
2911 Issue warning messages where appropriate.
2912 @item -nowarn
2913 Do not issue warning messages.
2914 @end table
2916 These options take effect at the point on the command line where they
2917 are specified.  Therefore it's not useful to specify @samp{-nowarn} at
2918 the end of the command line.  The warning messages affected by the
2919 above options are triggered by:
2921 @itemize @minus
2922 @item
2923 Use of the @samp{-d} option which is deprecated; please use
2924 @samp{-depth} instead, since the latter is POSIX-compliant.
2925 @item
2926 Use of the @samp{-ipath} option which is deprecated; please use
2927 @samp{-iwholename} instead.
2928 @item
2929 Specifying an option (for example @samp{-mindepth}) after a non-option
2930 (for example @samp{-type} or @samp{-print}) on the command line.
2931 @end itemize
2933 The default behaviour above is designed to work in that way so that
2934 existing shell scripts don't generate spurious errors, but people will
2935 be made aware of the problem.
2937 Some warning messages are issued for less common or more serious
2938 problems, and consequently cannot be turned off:
2940 @itemize @minus
2941 @item
2942 Use of an unrecognised backslash escape sequence with @samp{-fprintf}
2943 @item
2944 Use of an unrecognised formatting directive with @samp{-fprintf}
2945 @end itemize
2947 @node Optimisation Options
2948 @subsection Optimisation Options
2950 The @samp{-O@var{level}} option sets @code{find}'s optimisation level
2951 to @var{level}.  The default optimisation level is 1.
2953 At certain optimisation levels, @code{find} reorders tests to speed up
2954 execution while preserving the overall effect; that is, predicates
2955 with side effects are not reordered relative to each other.  The
2956 optimisations performed at each optimisation level are as follows.
2958 @table @samp
2959 @item 0
2960 Currently equivalent to optimisation level 1.
2962 @item 1
2963 This is the default optimisation level and corresponds to the
2964 traditional behaviour.  Expressions are reordered so that tests based
2965 only on the names of files (for example@samp{ -name} and
2966 @samp{-regex}) are performed first.
2968 @item 2 
2969 Any @samp{-type} or @samp{-xtype} tests are performed after any tests
2970 based only on the names of files, but before any tests that require
2971 information from the inode.  On many modern versions of Unix, file
2972 types are returned by @code{readdir()} and so these predicates are
2973 faster to evaluate than predicates which need to stat the file first.
2975 @item 3 
2976 At this optimisation level, the full cost-based query optimiser is
2977 enabled.  The order of tests is modified so that cheap (i.e., fast)
2978 tests are performed first and more expensive ones are performed later,
2979 if necessary.  Within each cost band, predicates are evaluated earlier
2980 or later according to whether they are likely to succeed or not.  For
2981 @samp{-o}, predicates which are likely to succeed are evaluated
2982 earlier, and for @samp{-a}, predicates which are likely to fail are
2983 evaluated earlier.
2984 @end table
2987 @node Debug Options
2988 @subsection Debug Options
2990 The @samp{-D} option makes @code{find} produce diagnostic output.
2991 Much of the information is useful only for diagnosing problems, and so
2992 most people will not find this option helpful.
2994 The list of debug options should be comma separated.  Compatibility of
2995 the debug options is not guaranteed between releases of findutils.
2996 For a complete list of valid debug options, see the output of
2997 @code{find -D help}.  Valid debug options include:
2998 @table @samp
2999 @item help
3000 Explain the debugging options.
3001 @item tree   
3002 Show the expression tree in its original and optimised form.
3003 @item stat   
3004 Print messages as files are examined with the stat and lstat system
3005 calls.  The find program tries to minimise such calls.
3006 @item opt    
3007 Prints diagnostic information relating to the optimisation of the
3008 expression tree; see the @samp{-O} option.
3009 @item rates
3010 Prints a summary indicating how often each predicate succeeded or
3011 failed.
3012 @end table
3014 @node Find Expressions
3015 @subsection Find Expressions
3017 The final part of the @code{find} command line is a list of
3018 expressions.  @xref{Primary Index}, for a summary of all of the tests,
3019 actions, and options that the expression can contain.  If the
3020 expression is missing, @samp{-print} is assumed.
3022 @node Invoking locate
3023 @section Invoking @code{locate}
3025 @example
3026 locate @r{[}@var{option}@dots{}@r{]} @var{pattern}@dots{}
3027 @end example
3029 For each @var{pattern} given @code{locate} searches one or more file
3030 name databases returning each match of @var{pattern}.
3032 For each @var{pattern} given @code{locate} searches one or more file
3033 name databases returning each match of @var{pattern}.
3035 @table @code
3036 @item --all
3037 @itemx -A
3038 Print only names which match all non-option arguments, not those
3039 matching one or more non-option arguments.
3041 @item --basename
3042 @itemx -b
3043 The specified pattern is matched against just the last component of
3044 the name of a file in the @code{locate} database.  This last
3045 component is also called the ``base name''.  For example, the base
3046 name of @file{/tmp/mystuff/foo.old.c} is @file{foo.old.c}.  If the
3047 pattern contains metacharacters, it must match the base name exactly.
3048 If not, it must match part of the base name.
3050 @item --count
3051 @itemx -c
3052 Instead of printing the matched file names, just print the total
3053 number of matches found, unless @samp{--print} (@samp{-p}) is also
3054 present.
3057 @item --database=@var{path}
3058 @itemx -d @var{path}
3059 Instead of searching the default @code{locate} database
3060 @file{@value{LOCATE_DB}}, @code{locate} searches the file
3061 name databases in @var{path}, which is a colon-separated list of
3062 database file names.  You can also use the environment variable
3063 @code{LOCATE_PATH} to set the list of database files to search.  The
3064 option overrides the environment variable if both are used.  Empty
3065 elements in @var{path} (that is, a leading or trailing colon, or two
3066 colons in a row) are taken to stand for the default database.
3067 A database can be supplied on stdin, using @samp{-} as an element
3068 of @samp{path}. If more than one element of @samp{path} is @samp{-},
3069 later instances are ignored (but a warning message is printed).
3071 @item --existing
3072 @itemx -e
3073 Only print out such names which currently exist (instead of such names
3074 which existed when the database was created).  Note that this may slow
3075 down the program a lot, if there are many matches in the database.
3076 The way in which broken symbolic links are treated is affected by the
3077 @samp{-L}, @samp{-P} and @samp{-H} options.  Please note that it is
3078 possible for the file to be deleted after @code{locate} has checked
3079 that it exists, but before you use it.  This option is automatically
3080 turned on when reading an @code{slocate} database in secure mode
3081 (@pxref{slocate Database Format}).
3083 @item --non-existing
3084 @itemx -E
3085 Only print out such names which currently do not exist (instead of
3086 such names which existed when the database was created).  Note that
3087 this may slow down the program a lot, if there are many matches in the
3088 database.  The way in which broken symbolic links are treated is
3089 affected by the @samp{-L}, @samp{-P} and @samp{-H} options.  Please
3090 note that @code{locate} checks that the file does not exist, but a
3091 file of the same name might be created after @code{locate}'s check but
3092 before you read @code{locate}'s output.
3094 @item --follow
3095 @itemx -L
3096 If testing for the existence of files (with the @samp{-e} or @samp{-E}
3097 options), consider broken symbolic links to be non-existing.  This is
3098 the default behaviour.  
3100 @item --nofollow
3101 @itemx -P
3102 @itemx -H
3103 If testing for the existence of files (with the @samp{-e} or @samp{-E}
3104 options), treat broken symbolic links as if they were existing files.
3105 The @samp{-H} form of this option is provided purely for similarity
3106 with @code{find}; the use of @samp{-P} is recommended over @samp{-H}.
3108 @item --ignore-case
3109 @itemx -i
3110 Ignore case distinctions in both the pattern and the file names.
3112 @item --limit=N
3113 @itemx -l N
3114 Limit the number of results printed to N.  When used with the
3115 @samp{--count} option, the value printed will never be larger than
3116 this limit.
3117 @item --max-database-age=D
3118 Normally, @code{locate} will issue a warning message when it searches
3119 a database which is more than 8 days old.  This option changes that
3120 value to something other than 8.  The effect of specifying a negative
3121 value is undefined.
3122 @item --mmap
3123 @itemx -m
3124 Accepted but does nothing.  The option is supported only to provide
3125 compatibility with BSD's @code{locate}.
3127 @item --null
3128 @itemx -0
3129 Results are separated with the ASCII NUL character rather than the
3130 newline character.  To get the full benefit of the use of this option,
3131 use the new @code{locate} database format (that is the default
3132 anyway).
3134 @item --print
3135 @itemx -p
3136 Print search results when they normally would not, because of the
3137 presence of @samp{--statistics} (@samp{-S}) or @samp{--count}
3138 (@samp{-c}).
3140 @item --wholename
3141 @itemx -w
3142 The specified pattern is matched against the whole name of the file in
3143 the @code{locate} database.  If the pattern contains metacharacters,
3144 it must match exactly.  If not, it must match part of the whole file
3145 name.  This is the default behaviour.
3147 @item --regex
3148 @itemx -r
3149 Instead of using substring or shell glob matching, the pattern
3150 specified on the command line is understood to be a regular
3151 expression.  GNU Emacs-style regular expressions are assumed unless
3152 the @samp{--regextype} option is also given.  File names from the
3153 @code{locate} database are matched using the specified regular
3154 expression.  If the @samp{-i} flag is also given, matching is
3155 case-insensitive.  Matches are performed against the whole path name,
3156 and so by default a pathname will be matched if any part of it matches
3157 the specified regular expression.  The regular expression may use
3158 @samp{^} or @samp{$} to anchor a match at the beginning or end of a
3159 pathname.
3161 @item --regextype
3162 This option changes the regular expression syntax and behaviour used
3163 by the @samp{--regex} option.  @ref{Regular Expressions} for more
3164 information on the regular expression dialects understood by GNU
3165 findutils.
3167 @item --stdio
3168 @itemx -s
3169 Accepted but does nothing.  The option is supported only to provide
3170 compatibility with BSD's @code{locate}.
3172 @item --statistics
3173 @itemx -S
3174 Print some summary information for each @code{locate} database.  No
3175 search is performed unless non-option arguments are given.
3176 Although the BSD version of locate also has this option, the format of the
3177 output is different.
3179 @item --help
3180 Print a summary of the command line usage for @code{locate} and exit.
3182 @item --version
3183 Print the version number of @code{locate} and exit.
3184 @end table
3186 @node Invoking updatedb
3187 @section Invoking @code{updatedb}
3189 @example
3190 updatedb @r{[}@var{option}@dots{}@r{]}
3191 @end example
3193 @code{updatedb} creates and updates the database of file names used by
3194 @code{locate}.  @code{updatedb} generates a list of files similar to
3195 the output of @code{find} and then uses utilities for optimizing the
3196 database for performance.  @code{updatedb} is often run periodically
3197 as a @code{cron} job and configured with environment variables or
3198 command options.  Typically, operating systems have a shell script
3199 that ``exports'' configurations for variable definitions and uses
3200 another shell script that ``sources'' the configuration file into the
3201 environment and then executes @code{updatedb} in the environment.
3203 @code{updatedb} creates and updates the database of file names used by
3204 @code{locate}.  @code{updatedb} generates a list of files similar to
3205 the output of @code{find} and then uses utilities for optimizing the
3206 database for performance.  @code{updatedb} is often run periodically
3207 as a @code{cron} job and configured with environment variables or
3208 command options.  Typically, operating systems have a shell script
3209 that ``exports'' configurations for variable definitions and uses
3210 another shell script that ``sources'' the configuration file into the
3211 environment and then executes @code{updatedb} in the environment.
3213 @table @code
3214 @item --findoptions='@var{OPTION}@dots{}'
3215 Global options to pass on to @code{find}.
3216 The environment variable @code{FINDOPTIONS} also sets this value.
3217 Default is none.
3219 @item --localpaths='@var{path}@dots{}'
3220 Non-network directories to put in the database.
3221 Default is @file{/}.
3223 @item --netpaths='@var{path}@dots{}'
3224 Network (NFS, AFS, RFS, etc.) directories to put in the database.
3225 The environment variable @code{NETPATHS} also sets this value.
3226 Default is none.
3228 @item --prunepaths='@var{path}@dots{}'
3229 Directories to omit from the database, which would otherwise be
3230 included.  The environment variable @code{PRUNEPATHS} also sets this
3231 value.  Default is @file{/tmp /usr/tmp /var/tmp /afs}.  The paths are
3232 used as regular expressions (with @code{find ... -regex}, so you need
3233 to specify these paths in the same way that @code{find} will encounter
3234 them.  This means for example that the paths must not include trailing
3235 slashes.
3237 @item --prunefs='@var{path}@dots{}'
3238 Filesystems to omit from the database, which would otherwise be
3239 included.  Note that files are pruned when a filesystem is reached;
3240 Any filesystem mounted under an undesired filesystem will be ignored.
3241 The environment variable @code{PRUNEFS} also sets this value.  Default
3242 is @file{nfs NFS proc}.
3244 @item --output=@var{dbfile}
3245 The database file to build.  The default is system-dependent, but
3246 when this document was formatted it was @file{@value{LOCATE_DB}}.
3248 @item --localuser=@var{user}
3249 The user to search the non-network directories as, using @code{su}.
3250 Default is to search the non-network directories as the current user.
3251 You can also use the environment variable @code{LOCALUSER} to set this user.
3253 @item --netuser=@var{user}
3254 The user to search network directories as, using @code{su}.  Default
3255 @code{user} is @code{daemon}.  You can also use the environment variable
3256 @code{NETUSER} to set this user.
3258 @item --old-format
3259 Generate a @code{locate} database in the old format, for compatibility
3260 with versions of @code{locate} other than GNU @code{locate}.  Using
3261 this option means that @code{locate} will not be able to properly
3262 handle non-ASCII characters in file names (that is, file names
3263 containing characters which have the eighth bit set, such as many of
3264 the characters from the ISO-8859-1 character set).  @xref{Database
3265 Formats}, for a detailed description of the supported database
3266 formats.
3268 @item --dbformat=@var{FORMAT}
3269 Generate the locate database in format @code{FORMAT}.  Supported
3270 database formats include @code{LOCATE02} (which is the default),
3271 @code{old} and @code{slocate}.  The @code{old} format exists for
3272 compatibility with implementations of @code{locate} on other Unix
3273 systems.  The @code{slocate} format exists for compatibility with
3274 @code{slocate}.  @xref{Database Formats}, for a detailed description
3275 of each format.
3277 @item --help
3278 Print a summary of the command line usage and exit.
3279 @item --version
3280 Print the version number of @code{updatedb} and exit.
3281 @end table
3283 @node Invoking xargs
3284 @section Invoking @code{xargs}
3286 @example
3287 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
3288 @end example
3290 @code{xargs} exits with the following status:
3292 @table @asis
3293 @item 0
3294 if it succeeds
3295 @item 123
3296 if any invocation of the command exited with status 1-125
3297 @item 124
3298 if the command exited with status 255
3299 @item 125
3300 if the command is killed by a signal
3301 @item 126
3302 if the command cannot be run
3303 @item 127
3304 if the command is not found
3305 @item 1
3306 if some other error occurred.
3307 @end table
3309 Exit codes greater than 128 are used by the shell to indicate that 
3310 a program died due to a fatal signal.
3311   
3312 @table @code
3313 @item --arg-file@r{=@var{inputfile}}
3314 @itemx -a o@r{@var{inputfile}}
3315 Read names from the file @var{inputfile} instead of standard input.
3316 If you use this option, the standard input stream remains unchanged
3317 when commands are run. Otherwise, stdin is redirected from
3318 @file{/dev/null}.
3320 @item --null
3321 @itemx -0
3322 Input file names are terminated by a null character instead of by
3323 whitespace, and any quotes and backslash characters are not considered
3324 special (every character is taken literally).  Disables the end of
3325 file string, which is treated like any other argument.
3327 @item --delimiter @var{delim}
3328 @itemx -d @var{delim}
3330 Input file names are terminated by the specified character @var{delim}
3331 instead of by whitespace, and any quotes and backslash characters are
3332 not considered special (every character is taken literally).  Disables
3333 the end of file string, which is treated like any other argument.
3335 The specified delimiter may be a single character, a C-style character
3336 escape such as @samp{\n}, or an octal or hexadecimal escape code.
3337 Octal and hexadecimal escape codes are understood as for the
3338 @code{printf} command.  Multibyte characters are not supported.
3341 @item -E @var{eof-str}
3342 @itemx --eof@r{[}=@var{eof-str}@r{]}
3343 @itemx -e@r{[}@var{eof-str}@r{]}
3344 Set the end of file string to @var{eof-str}.  If the end of file
3345 string occurs as a line of input, the rest of the input is ignored.
3346 If @var{eof-str} is omitted (@samp{-e}) or blank (either @samp{-e} or
3347 @samp{-E}), there is no end of file string.  The @samp{-e} form of
3348 this option is deprecated in favour of the POSIX-compliant @samp{-E}
3349 option, which you should use instead.  As of GNU xargs version 4.2.9,
3350 the default behaviour of xargs is not to have a logical end-of-file
3351 marker.  The POSIX standard (IEEE Std 1003.1, 2004 Edition) allows
3352 this.
3354 @item --help
3355 Print a summary of the options to @code{xargs} and exit.
3357 @item -I @var{replace-str}
3358 @itemx --replace@r{[}=@var{replace-str}@r{]}
3359 @itemx -i@r{[}@var{replace-str}@r{]}
3360 Replace occurrences of @var{replace-str} in the initial arguments with
3361 names read from standard input.  Also, unquoted blanks do not
3362 terminate arguments; instead, the input is split at newlines only.  If
3363 @var{replace-str} is omitted (omitting it is allowed only for
3364 @samp{-i}), it defaults to @samp{@{@}} (like for @samp{find -exec}).
3365 Implies @samp{-x} and @samp{-l 1}.  The @samp{-i} option is deprecated
3366 in favour of the @samp{-I} option.
3368 @item -L @var{max-lines}
3369 @itemx --max-lines@r{[}=@var{max-lines}@r{]}
3370 @itemx -l@r{[}@var{max-lines}@r{]}
3371 Use at most @var{max-lines} non-blank input lines per command line.
3372 For @samp{-l}, @var{max-lines} defaults to 1 if omitted.  For
3373 @samp{-L}, the argument is mandatory.  Trailing blanks cause an input
3374 line to be logically continued on the next input line, for the purpose
3375 of counting the lines.  Implies @samp{-x}.  The @samp{-l} form of this
3376 option is deprecated in favour of the POSIX-compliant @samp{-L}
3377 option.
3379 @item --max-args=@var{max-args}
3380 @itemx -n @var{max-args}
3381 Use at most @var{max-args} arguments per command line.  Fewer than
3382 @var{max-args} arguments will be used if the size (see the @samp{-s}
3383 option) is exceeded, unless the @samp{-x} option is given, in which
3384 case @code{xargs} will exit.
3386 @item --interactive
3387 @itemx -p
3388 Prompt the user about whether to run each command line and read a line
3389 from the terminal.  Only run the command line if the response starts
3390 with @samp{y} or @samp{Y}.  Implies @samp{-t}.
3392 @item --no-run-if-empty
3393 @itemx -r
3394 If the standard input is completely empty, do not run the
3395 command.  By default, the command is run once even if there is no
3396 input.
3398 @item --max-chars=@var{max-chars}
3399 @itemx -s @var{max-chars}
3400 Use at most @var{max-chars} characters per command line, including the
3401 command, initial arguments and any terminating nulls at the ends of
3402 the argument strings.
3404 @item --show-limits
3405 Display the limits on the command-line length which are imposed by the
3406 operating system, @code{xargs}' choice of buffer size and the
3407 @samp{-s} option.  Pipe the input from @file{/dev/null} (and perhaps
3408 specify @samp{--no-run-if-empty}) if you don't want @code{xargs} to do
3409 anything.
3411 @item --verbose
3412 @itemx -t
3413 Print the command line on the standard error output before executing
3416 @item --version
3417 Print the version number of @code{xargs} and exit.
3419 @item --exit
3420 @itemx -x
3421 Exit if the size (see the @samp{-s} option) is exceeded.
3424 @item --max-procs=@var{max-procs}
3425 @itemx -P @var{max-procs}
3426 Run simultaneously up to @var{max-procs} processes at once; the default is 1.  If
3427 @var{max-procs} is 0, @code{xargs} will run as many processes as
3428 possible simultaneously.
3429 @end table
3432 @node Regular Expressions
3433 @section Regular Expressions
3435 The @samp{-regex} and @samp{-iregex} tests of @code{find} allow
3436 matching by regular expression, as does the @samp{--regex} option of
3437 @code{locate}.  There are many different types of Regular Expression,
3438 but the type used by @code{find} and @code{locate} is the same as is
3439 used in GNU Emacs.  Both programs provide an option which allows you
3440 to select an alternative regular expression syntax; for @code{find}
3441 this is the @samp{-regextype} option, and for @code{locate} this is
3442 the @samp{--regextype} option.
3444 These options take a single argument, which indicates the specific
3445 regular expression syntax and behaviour that should be used.  This
3446 should be one of the following:
3448 @include regexprops.texi
3450 @node Environment Variables
3451 @section Environment Variables
3452 @table @var
3453 @item LANG
3454 Provides a default value for the internationalisation variables that
3455 are unset or null.
3456 @item LC_ALL
3457 If set to a non-empty string value, override the values of all the
3458 other internationalisation variables.
3459 @item LC_COLLATE
3460 The POSIX standard specifies that this variable affects the pattern
3461 matching to be used for the `\-name' option.  GNU find uses the
3462 GNU version of the @code{fnmatch} library function.
3464 POSIX also specifies that the `LC_COLLATE' environment 
3465 variable affects the interpretation of the user's response to the 
3466 query issued by `\-ok', but this is not the case for GNU find.
3467 @item LC_CTYPE 
3468 This variable affects the treatment of character classes used with 
3469 the @samp{-name} test, if the system's 
3470 @code{fnmatch} library function supports this.   It has no effect on the behaviour 
3471 of the @samp{-ok} expression.
3472 @item LC_MESSAGES
3473 Determines the locale to be used for internationalised messages.
3474 @item NLSPATH
3475 Determines the location of the internationalisation message catalogues.
3476 @item PATH
3477 Affects the directories which are searched to find the executables
3478 invoked by @samp{-exec}, @samp{-execdir} @samp{-ok} and @samp{-okdir}.
3479 If the @var{PATH} environment variable includes the current directory
3480 (by explicitly including @samp{.} or by having an empty element), and
3481 the find command line includes @samp{-execdir} or @samp{-okdir},
3482 @code{find} will refuse to run.  @xref{Security Considerations}, for a
3483 more detailed discussion of security matters.
3485 @item POSIXLY_CORRECT 
3486 Determines the block size used by @samp{-ls} and @samp{-fls}.  
3487 If @var{POSIXLY_CORRECT} is set, blocks are units of 512 bytes.  Otherwise
3488 they are units of 1024 bytes.
3490 @item TZ 
3491 Affects the time zone used for some of the time-related format
3492 directives of @samp{-printf} and @samp{-fprintf}.
3493 @end table
3497 @node Common Tasks
3498 @chapter Common Tasks
3500 The sections that follow contain some extended examples that both give
3501 a good idea of the power of these programs, and show you how to solve
3502 common real-world problems.
3504 @menu
3505 * Viewing And Editing::
3506 * Archiving::
3507 * Cleaning Up::
3508 * Strange File Names::
3509 * Fixing Permissions::
3510 * Classifying Files::
3511 @end menu
3513 @node Viewing And Editing
3514 @section Viewing And Editing
3516 To view a list of files that meet certain criteria, simply run your
3517 file viewing program with the file names as arguments.  Shells
3518 substitute a command enclosed in backquotes with its output, so the
3519 whole command looks like this:
3521 @example
3522 less `find /usr/include -name '*.h' | xargs grep -l mode_t`
3523 @end example
3525 @noindent
3526 You can edit those files by giving an editor name instead of a file
3527 viewing program:
3529 @example
3530 emacs `find /usr/include -name '*.h' | xargs grep -l mode_t`
3531 @end example
3533 Because there is a limit to the length of any individual command line,
3534 there is a limit to the number of files that can be handled in this
3535 way.  We can get around this difficulty by using xargs like this:
3537 @example
3538 find /usr/include -name '*.h' | xargs grep -l mode_t > todo
3539 xargs --arg-file=todo emacs
3540 @end example
3542 Here, @code{xargs} will run @code{emacs} as many times as necessary to
3543 visit all of the files listed in the file @file{todo}.
3545 @node Archiving
3546 @section Archiving
3548 You can pass a list of files produced by @code{find} to a file
3549 archiving program.  GNU @code{tar} and @code{cpio} can both read lists
3550 of file names from the standard input---either delimited by nulls (the
3551 safe way) or by blanks (the lazy, risky default way).  To use
3552 null-delimited names, give them the @samp{--null} option.  You can
3553 store a file archive in a file, write it on a tape, or send it over a
3554 network to extract on another machine.
3556 One common use of @code{find} to archive files is to send a list of
3557 the files in a directory tree to @code{cpio}.  Use @samp{-depth} so if
3558 a directory does not have write permission for its owner, its contents
3559 can still be restored from the archive since the directory's
3560 permissions are restored after its contents.  Here is an example of
3561 doing this using @code{cpio}; you could use a more complex @code{find}
3562 expression to archive only certain files.
3564 @example
3565 find . -depth -print0 |
3566   cpio --create --null --format=crc --file=/dev/nrst0
3567 @end example
3569 You could restore that archive using this command:
3571 @example
3572 cpio --extract --null --make-dir --unconditional \
3573   --preserve --file=/dev/nrst0
3574 @end example
3576 Here are the commands to do the same things using @code{tar}:
3578 @example
3579 find . -depth -print0 |
3580   tar --create --null --files-from=- --file=/dev/nrst0
3582 tar --extract --null --preserve-perm --same-owner \
3583   --file=/dev/nrst0
3584 @end example
3586 @c Idea from Rick Sladkey.
3587 Here is an example of copying a directory from one machine to another:
3589 @example
3590 find . -depth -print0 | cpio -0o -Hnewc |
3591   rsh @var{other-machine} "cd `pwd` && cpio -i0dum"
3592 @end example
3594 @node Cleaning Up
3595 @section Cleaning Up
3597 @c Idea from Jim Meyering.
3598 This section gives examples of removing unwanted files in various
3599 situations.  Here is a command to remove the CVS backup files created
3600 when an update requires a merge:
3602 @example
3603 find . -name '.#*' -print0 | xargs -0r rm -f
3604 @end example
3606 The command above works, but the following is safer:
3608 @example
3609 find . -name '.#*' -depth -delete
3610 @end example
3612 @c Idea from Franc,ois Pinard.
3613 You can run this command to clean out your clutter in @file{/tmp}.
3614 You might place it in the file your shell runs when you log out
3615 (@file{.bash_logout}, @file{.logout}, or @file{.zlogout}, depending on
3616 which shell you use).
3618 @example
3619 find /tmp -depth -user "$LOGNAME" -type f -delete
3620 @end example
3622 If your @code{find} command removes directories, you may find that
3623 you get a spurious error message when @code{find} tries to recurse
3624 into a directory that has now been removed.  Using the @samp{-depth}
3625 option will normally resolve this problem.
3627 @c Idea from Noah Friedman.
3628 To remove old Emacs backup and auto-save files, you can use a command
3629 like the following.  It is especially important in this case to use
3630 null-terminated file names because Emacs packages like the VM mailer
3631 often create temporary file names with spaces in them, like
3632 @file{#reply to David J. MacKenzie<1>#}.
3634 @example
3635 find ~ \( -name '*~' -o -name '#*#' \) -print0 |
3636   xargs --no-run-if-empty --null rm -vf
3637 @end example
3639 Removing old files from @file{/tmp} is commonly done from @code{cron}:
3641 @c Idea from Kaveh Ghazi.
3642 @example
3643 find /tmp /var/tmp -not -type d -mtime +3 -delete
3644 find /tmp /var/tmp -depth -mindepth 1 -type d -empty -delete
3645 @end example
3647 The second @code{find} command above uses @samp{-depth} so it cleans
3648 out empty directories depth-first, hoping that the parents become
3649 empty and can be removed too.  It uses @samp{-mindepth} to avoid
3650 removing @file{/tmp} itself if it becomes totally empty.
3652 @node Strange File Names
3653 @section Strange File Names
3655 @c Idea from:
3656 @c From: tmatimar@isgtec.com (Ted Timar)
3657 @c Newsgroups: comp.unix.questions,comp.unix.shell,comp.answers,news.answers
3658 @c Subject: Unix - Frequently Asked Questions (2/7) [Frequent posting]
3659 @c Subject: How do I remove a file with funny characters in the filename ?
3660 @c Date: Thu Mar 18 17:16:55 EST 1993
3661 @code{find} can help you remove or rename a file with strange
3662 characters in its name.  People are sometimes stymied by files whose
3663 names contain characters such as spaces, tabs, control characters, or
3664 characters with the high bit set.  The simplest way to remove such
3665 files is:
3667 @example
3668 rm -i @var{some*pattern*that*matches*the*problem*file}
3669 @end example
3671 @code{rm} asks you whether to remove each file matching the given
3672 pattern.  If you are using an old shell, this approach might not work
3673 if the file name contains a character with the high bit set; the shell
3674 may strip it off.  A more reliable way is:
3676 @example
3677 find . -maxdepth 1 @var{tests} -okdir rm '@{@}' \;
3678 @end example
3680 @noindent
3681 where @var{tests} uniquely identify the file.  The @samp{-maxdepth 1}
3682 option prevents @code{find} from wasting time searching for the file
3683 in any subdirectories; if there are no subdirectories, you may omit
3684 it.  A good way to uniquely identify the problem file is to figure out
3685 its inode number; use
3687 @example
3688 ls -i
3689 @end example
3691 Suppose you have a file whose name contains control characters, and
3692 you have found that its inode number is 12345.  This command prompts
3693 you for whether to remove it:
3695 @example
3696 find . -maxdepth 1 -inum 12345 -okdir rm -f '@{@}' \;
3697 @end example
3699 If you don't want to be asked, perhaps because the file name may
3700 contain a strange character sequence that will mess up your screen
3701 when printed, then use @samp{-execdir} instead of @samp{-okdir}.
3703 If you want to rename the file instead, you can use @code{mv} instead
3704 of @code{rm}:
3706 @example
3707 find . -maxdepth 1 -inum 12345 -okdir mv '@{@}' @var{new-file-name} \;
3708 @end example
3710 @node Fixing Permissions
3711 @section Fixing Permissions
3713 Suppose you want to make sure that everyone can write to the
3714 directories in a certain directory tree.  Here is a way to find
3715 directories lacking either user or group write permission (or both),
3716 and fix their permissions:
3718 @example
3719 find . -type d -not -perm -ug=w | xargs chmod ug+w
3720 @end example
3722 @noindent
3723 You could also reverse the operations, if you want to make sure that
3724 directories do @emph{not} have world write permission.
3726 @node Classifying Files
3727 @section Classifying Files
3729 @c Idea from:
3730 @c From: martin@mwtech.UUCP (Martin Weitzel)
3731 @c Newsgroups: comp.unix.wizards,comp.unix.questions
3732 @c Subject: Advanced usage of 'find' (Re: Unix security automating script)
3733 @c Date: 22 Mar 90 15:05:19 GMT
3734 If you want to classify a set of files into several groups based on
3735 different criteria, you can use the comma operator to perform multiple
3736 independent tests on the files.  Here is an example:
3738 @example
3739 find / -type d \( -perm -o=w -fprint allwrite , \
3740   -perm -o=x -fprint allexec \)
3742 echo "Directories that can be written to by everyone:"
3743 cat allwrite
3744 echo ""
3745 echo "Directories with search permissions for everyone:"
3746 cat allexec
3747 @end example
3749 @code{find} has only to make one scan through the directory tree
3750 (which is one of the most time consuming parts of its work).
3752 @node Worked Examples
3753 @chapter Worked Examples
3755 The tools in the findutils package, and in particular @code{find},
3756 have a large number of options.  This means that quite often,
3757 there is more than one way to do things.  Some of the options
3758 and facilities only exist for compatibility with other tools, and
3759 findutils provides improved ways of doing things.
3761 This chapter describes a number of useful tasks that are commonly
3762 performed, and compares the different ways of achieving them.
3764 @menu
3765 * Deleting Files::
3766 * Updating A Timestamp File::
3767 @end menu
3769 @node Deleting Files
3770 @section Deleting Files
3772 One of the most common tasks that @code{find} is used for is locating
3773 files that can be deleted.  This might include:
3775 @itemize
3776 @item 
3777 Files last modified more than 3 years ago which haven't been accessed
3778 for at least 2 years
3779 @item
3780 Files belonging to a certain user
3781 @item
3782 Temporary files which are no longer required
3783 @end itemize
3785 This example concentrates on the actual deletion task rather than on
3786 sophisticated ways of locating the files that need to be deleted.
3787 We'll assume that the files we want to delete are old files underneath
3788 @file{/var/tmp/stuff}.
3790 @subsection The Traditional Way
3792 The traditional way to delete files in @file{var/tmp/stuff} that have
3793 not been modified in over 90 days would have been:
3795 @smallexample
3796 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \;
3797 @end smallexample
3799 The above command uses @samp{-exec} to run the @code{/bin/rm} command
3800 to remove each file.  This approach works and in fact would have
3801 worked in Version 7 Unix in 1979.  However, there are a number of
3802 problems with this approach.
3805 The most obvious problem with the approach above is that it causes
3806 @code{find} to fork every time it finds a file that needs to delete,
3807 and the child process then has to use the @code{exec} system call to
3808 launch @code{/bin/rm}.   All this is quite inefficient.  If we are
3809 going to use @code{/bin/rm} to do this job, it is better to make it
3810 delete more than one file at a time.  
3812 The most obvious way of doing this is to use the shell's command
3813 expansion feature:
3815 @smallexample
3816 /bin/rm `find /var/tmp/stuff -mtime +90 -print`
3817 @end smallexample
3818 or you could use the more modern form
3819 @smallexample
3820 /bin/rm $(find /var/tmp/stuff -mtime +90 -print)
3821 @end smallexample
3823 The commands above are much more efficient than the first attempt.
3824 However, there is a problem with them.  The shell has a maximum
3825 command length which is imposed by the operating system (the actual
3826 limit varies between systems).  This means that while the command
3827 expansion technique will usually work, it will suddenly fail when
3828 there are lots of files to delete.  Since the task is to delete
3829 unwanted files, this is precisely the time we don't want things to go
3830 wrong.
3832 @subsection Making Use of xargs
3834 So, is there a way to be more efficient in the use of @code{fork()}
3835 and @code{exec()} without running up against this limit?
3836 Yes, we can be almost optimally efficient by making use
3837 of the @code{xargs} command.  The @code{xargs} command reads arguments
3838 from its standard input and builds them into command lines.  We can
3839 use it like this:
3841 @smallexample
3842 find /var/tmp/stuff -mtime +90 -print | xargs /bin/rm 
3843 @end smallexample
3845 For example if the files found by @code{find} are
3846 @file{/var/tmp/stuff/A}, 
3847 @file{/var/tmp/stuff/B} and 
3848 @file{/var/tmp/stuff/C} then @code{xargs} might issue the commands 
3850 @smallexample
3851 /bin/rm /var/tmp/stuff/A /var/tmp/stuff/B
3852 /bin/rm /var/tmp/stuff/C
3853 @end smallexample
3855 The above assumes that @code{xargs} has a very small maximum command
3856 line length.  The real limit is much larger but the idea is that
3857 @code{xargs} will run @code{/bin/rm} as many times as necessary to get
3858 the job done, given the limits on command line length.
3860 This usage of @code{xargs} is pretty efficient, and the @code{xargs}
3861 command is widely implemented (all modern versions of Unix offer it).
3862 So far then, the news is all good.  However, there is bad news too.
3864 @subsection Unusual characters in filenames
3866 Unix-like systems allow any characters to appear in file names with
3867 the exception of the ASCII NUL character and the backslash.
3868 Backslashes can occur in path names (as the directory separator) but
3869 not in the names of actual directory entries.  This means that the
3870 list of files that @code{xargs} reads could in fact contain white space
3871 characters --- spaces, tabs and newline characters.  Since by default,
3872 @code{xargs} assumes that the list of files it is reading uses white
3873 space as an argument separator, it cannot correctly handle the case
3874 where a filename actually includes white space.  This makes the
3875 default behaviour of @code{xargs} almost useless for handling
3876 arbitrary data.
3878 To solve this problem, GNU findutils introduced the @samp{-print0}
3879 action for @code{find}.  This uses the ASCII NUL character to separate
3880 the entries in the file list that it produces.  This is the ideal
3881 choice of separator since it is the only character that cannot appear
3882 within a path name.  The @samp{-0} option to @code{xargs} makes it
3883 assume that arguments are separated with ASCII NUL instead of white
3884 space.  It also turns off another misfeature in the default behaviour
3885 of @code{xargs}, which is that it pays attention to quote characters
3886 in its input.  Some versions of @code{xargs} also terminate when they
3887 see a lone @samp{_} in the input, but GNU @code{find} no longer does
3888 that (since it has become an optional behaviour in the Unix standard).
3890 So, putting @code{find -print0} together with @code{xargs -0} we get
3891 this command:
3893 @smallexample
3894 find /var/tmp/stuff -mtime +90 -print0 | xargs -0 /bin/rm 
3895 @end smallexample
3897 The result is an efficient way of proceeding that
3898 correctly handles all the possible characters that could appear in the
3899 list of files to delete.  This is good news.  However, there is, as
3900 I'm sure you're expecting, also more bad news.  The problem is that
3901 this is not a portable construct; although other versions of Unix
3902 (notable BSD-derived ones) support @samp{-print0}, it's not
3903 universal.  So, is there a more universal mechanism?
3905 @subsection Going back to -exec
3907 There is indeed a more universal mechanism, which is a slight
3908 modification to the @samp{-exec} action.  The normal @samp{-exec}
3909 action assumes that the command to run is terminated with a semicolon
3910 (the semicolon normally has to be quoted in order to protect it from
3911 interpretation as the shell command separator).  The SVR4 edition of
3912 Unix introduced a slight variation, which involves terminating the
3913 command with @samp{+} instead:
3915 @smallexample
3916 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \+
3917 @end smallexample
3919 The above use of @samp{-exec} causes @code{find} to build up a long
3920 command line and then issue it.  This can be less efficient than some
3921 uses of @code{xargs}; for example @code{xargs} allows new command
3922 lines to be built up while the previous command is still executing, and
3923 allows you to specify a number of commands to run in parallel.
3924 However, the @code{find @dots{} -exec @dots{} +} construct has the advantage
3925 of wide portability.  GNU findutils did not support @samp{-exec @dots{} +}
3926 until version 4.2.12; one of the reasons for this is that it already
3927 had the @samp{-print0} action in any case.
3930 @subsection A more secure version of -exec
3932 The command above seems to be efficient and portable.  However,
3933 within it lurks a security problem.  The problem is shared with
3934 all the commands we've tried in this worked example so far, too.  The
3935 security problem is a race condition; that is, if it is possible for
3936 somebody to manipulate the filesystem that you are searching while you
3937 are searching it, it is possible for them to persuade your @code{find}
3938 command to cause the deletion of a file that you can delete but they
3939 normally cannot.  
3941 The problem occurs because the @samp{-exec} action is defined by the
3942 @acronym{POSIX} standard to invoke its command with the same working directory
3943 as @code{find} had when it was started.  This means that the arguments
3944 which replace the @{@} include a relative path from @code{find}'s
3945 starting point down the file that needs to be deleted.  For example,
3947 @smallexample
3948 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \+
3949 @end smallexample
3951 might actually issue the command:
3953 @smallexample
3954 /bin/rm /var/tmp/stuff/A /var/tmp/stuff/B /var/tmp/stuff/passwd
3955 @end smallexample
3957 Notice the file @file{/var/tmp/stuff/passwd}.  Likewise, the command:
3959 @smallexample
3960 cd /var/tmp && find stuff -mtime +90 -exec /bin/rm @{@} \+
3961 @end smallexample
3963 might actually issue the command:
3965 @smallexample
3966 /bin/rm stuff/A stuff/B stuff/passwd
3967 @end smallexample
3969 If an attacker can rename @file{stuff} to something else (making use
3970 of their write permissions in @file{/var/tmp}) they can replace it
3971 with a symbolic link to @file{/etc}.  That means that the
3972 @code{/bin/rm} command will be invoked on @file{/etc/passwd}.  If you
3973 are running your @code{find} command as root, the attacker has just managed
3974 to delete a vital file.  All they needed to do to achieve this was
3975 replace a subdirectory with a symbolic link at the vital moment.
3977 There is however, a simple solution to the problem.  This is an action
3978 which works a lot like @code{-exec} but doesn't need to traverse a
3979 chain of directories to reach the file that it needs to work on.  This
3980 is the @samp{-execdir} action, which was introduced by the BSD family
3981 of operating systems.   The command,
3983 @smallexample
3984 find /var/tmp/stuff -mtime +90 -execdir /bin/rm @{@} \+
3985 @end smallexample
3987 might delete a set of files by performing these actions:
3989 @enumerate
3990 @item 
3991 Change directory to /var/tmp/stuff/foo
3992 @item 
3993 Invoke @code{/bin/rm ./file1 ./file2 ./file3}
3994 @item
3995 Change directory to /var/tmp/stuff/bar
3996 @item 
3997 Invoke @code{/bin/rm ./file99 ./file100 ./file101}
3998 @end enumerate
4000 This is a much more secure method.  We are no longer exposed to a race
4001 condition.  For many typical uses of @code{find}, this is the best
4002 strategy.   It's reasonably efficient, but the length of the command
4003 line is limited not just by the operating system limits, but also by
4004 how many files we actually need to delete from each directory.
4006 Is it possible to do any better?   In the case of general file
4007 processing, no.  However, in the specific case of deleting files it is
4008 indeed possible to do better.  
4010 @subsection Using the -delete action
4012 The most efficient and secure method of solving this problem is to use
4013 the @samp{-delete} action:
4015 @smallexample
4016 find /var/tmp/stuff -mtime +90 -delete
4017 @end smallexample
4019 This alternative is more efficient than any of the @samp{-exec} or
4020 @samp{-execdir} actions, since it entirely avoids the overhead of
4021 forking a new process and using @code{exec} to run @code{/bin/rm}.  It
4022 is also normally more efficient than @code{xargs} for the same
4023 reason.   The file deletion is performed from the directory containing
4024 the entry to be deleted, so the @samp{-delete} action has the same
4025 security advantages as the @samp{-execdir} action has.  
4027 The @samp{-delete} action was introduced by the BSD family of
4028 operating systems.
4030 @subsection Improving things still further
4032 Is it possible to improve things still further?  Not without either
4033 modifying the system library to the operating system or having more specific
4034 knowledge of the layout of the filesystem and disk I/O subsystem, or
4035 both.
4037 The @code{find} command traverses the filesystem, reading
4038 directories.  It then issues a separate system call for each file to
4039 be deleted.  If we could modify the operating system, there are
4040 potential gains that could be made:
4042 @itemize
4043 @item
4044 We could have a system call to which we pass more than one filename
4045 for deletion
4046 @item
4047 Alternatively, we could pass in a list of inode numbers (on GNU/Linux
4048 systems, @code{readdir()} also returns the inode number of each
4049 directory entry) to be deleted.
4050 @end itemize
4052 The above possibilities sound interesting, but from the kernel's point
4053 of view it is difficult to enforce standard Unix access controls for
4054 such processing by inode number.  Such a facility would probably
4055 need to be restricted to the superuser.
4057 Another way of improving performance would be to increase the
4058 parallelism of the process.  For example if the directory hierarchy we
4059 are searching is actually spread across a number of disks, we might
4060 somehow be able to arrange for @code{find} to process each disk in
4061 parallel.  In practice GNU @code{find} doesn't have such an intimate
4062 understanding of the system's filesystem layout and disk I/O
4063 subsystem.
4065 However, since the system administrator can have such an understanding
4066 they can take advantage of it like so:
4068 @smallexample
4069 find /var/tmp/stuff1 -mtime +90 -delete &
4070 find /var/tmp/stuff2 -mtime +90 -delete &
4071 find /var/tmp/stuff3 -mtime +90 -delete &
4072 find /var/tmp/stuff4 -mtime +90 -delete &
4073 wait
4074 @end smallexample
4076 In the example above, four separate instances of @code{find} are used
4077 to search four subdirectories in parallel.  The @code{wait} command
4078 simply waits for all of these to complete.  Whether this approach is
4079 more or less efficient than a single instance of @code{find} depends
4080 on a number of things:
4082 @itemize
4083 @item
4084 Are the directories being searched in parallel actually on separate
4085 disks?  If not, this parallel search might just result in a lot of
4086 disk head movement and so the speed might even be slower.
4087 @item
4088 Other activity - are other programs also doing things on those disks?
4089 @end itemize
4092 @subsection Conclusion
4094 The fastest and most secure way to delete files with the help of
4095 @code{find} is to use @samp{-delete}.  Using @code{xargs -0 -P N} can
4096 also make effective use of the disk, but it is not as secure.
4098 In the case where we're doing things other than deleting files, the
4099 most secure alternative is @samp{-execdir @dots{} +}, but this is not as
4100 portable as the insecure action @samp{-exec @dots{} +}.
4102 The @samp{-delete} action is not completely portable, but the only
4103 other possibility which is as secure (@samp{-execdir}) is no more
4104 portable.  The most efficient portable alternative is @samp{-exec
4105 @dots{}+}, but this is insecure and isn't supported by versions of GNU
4106 findutils prior to 4.2.12.
4109 @node Updating A Timestamp File
4110 @section Updating A Timestamp File
4112 Suppose we have a directory full of files which is maintained with a
4113 set of automated tools; perhaps one set of tools updates them and
4114 another set of tools uses the result.  In this situation, it might be
4115 useful for the second set of tools to know if the files have recently
4116 been changed.  It might be useful, for example, to have a 'timestamp'
4117 file which gives the timestamp on the newest file in the collection.
4119 We can use @code{find} to achieve this, but there are several
4120 different ways to do it.
4122 @subsection Updating the Timestamp The Wrong Way
4124 The obvious but wrong answer is just to use @samp{-newer}:-
4126 @smallexample
4127 find subdir -newer timestamp -exec touch -r @{@} timestamp \; 
4128 @end smallexample
4130 This does the right sort of thing but has a bug.  Suppose that two
4131 files in the subdirectory have been updated, and that these are called
4132 @file{file1} and @file{file2}.  The command above will update
4133 @file{timestamp} with the modification time of @file{file1} or that of
4134 @file{file2}, but we don't know which one.  Since the timestamps on
4135 @file{file1} and @file{file2} will in general be different, this could
4136 well be the wrong value.
4138 One solution to this problem is to modify @code{find} to recheck the
4139 modification time of @file{timestamp} every time a file is to be
4140 compared against it, but that will reduce the performance of
4141 @code{find}.
4143 @subsection Using the test utility to compare timestamps
4145 The @code{test} command can be used to compare timestamps:
4147 @smallexample
4148 find subdir -exec test @{@} -nt timestamp \; -exec touch -r @{@} timestamp \; 
4149 @end smallexample
4151 This will ensure that any changes made to the modification time of
4152 @file{timestamp} that take place during the execution of @code{find}
4153 are taken into account.  This resolves our earlier problem, but
4154 unfortunately this runs much more slowly.
4156 @subsection A combined approach
4158 We can of course still use @samp{-newer} to cut down on the number of
4159 calls to @code{test}:
4161 @smallexample
4162 find subdir -newer timestamp -a \
4163      -exec test @{@} -nt timestamp \; -a \
4164      -exec touch -r @{@} timestamp \; 
4165 @end smallexample
4167 Here, the @samp{-newer} test excludes all the files which are
4168 definitely older than the timestamp, but all the files which are newer
4169 than the old value of the timestamp are compared against the current
4170 updated timestamp.
4172 This is indeed faster in general, but the speed difference will depend
4173 on how many updated files there are.
4175 @subsection Using -printf and sort to compare timestamps
4177 It is possible to use the @samp{-printf} action to abandon the use of
4178 @code{test} entirely:
4180 @smallexample
4181 newest=$(find subdir -newer timestamp -printf "%A@:%p\n" | 
4182            sort -n | 
4183            tail -1 | 
4184            cut -d: -f2- ) 
4185 touch -r "$@{newest:-timestamp@}" timestamp
4186 @end smallexample
4188 The command above works by generating a list of the timestamps and
4189 names of all the files which are newer than the timestamp.  The
4190 @code{sort}, @code{tail} and @code{cut} commands simply pull out the
4191 name of the file with the largest timestamp value (that is, the latest
4192 file).  The @code{touch} command is then used to update the timestamp,
4194 The @code{"$@{newest:-timestamp@}"} expression simply expands to the
4195 value of @code{$newest} if that variable is set, but to
4196 @file{timestamp} otherwise.  This ensures that an argument is always
4197 given to the @samp{-r} option of the @code{touch} command.
4199 This approach seems quite efficient, but unfortunately it has a bug.
4200 Many operating systems now keep file modification time information at
4201 a granularity which is finer than one second.  Unfortunately the
4202 @samp{%A@@} format for @samp{-printf} only prints a whole-number value
4203 currently; that is, these values are at a one-second granularity.
4204 This means that in our example above, @samp{$newest} will be the name
4205 of a file which is no more than one second older than the newest file,
4206 but may indeed be older.
4208 It would be possible to solve this problem with some kind of loop:
4210 @smallexample
4211 while true; do
4212         newest=$(find subdir -newer timestamp -printf "%A@@:%p\n" | 
4213            sort -n | 
4214            tail -1 | 
4215            cut -d: -f2- ) 
4216         if test -z "$newest" ; then
4217                 break
4218         else
4219                 touch -r "$newest" timestamp
4220         fi
4221 done
4222 @end smallexample
4224 A better fix for this problem would be to allow the @samp{%A@@} format
4225 to produce a result having a fractional part, too.  While this is
4226 planned for GNU @code{find}, it hasn't been done yet.
4228 @subsection Coping with sub-second timestamp resolution
4230 Another tool which often works with timestamps is @code{make}.  We can
4231 use @code{find} to generate a @file{Makefile} file on the fly and then
4232 use @code{make} to update the timestamps:
4234 @smallexample
4235 makefile=$(mktemp)
4236 find subdir \
4237         \( \! -xtype l \) \
4238         -newer timestamp \
4239         -printf "timestamp:: %p\n\ttouch -r %p timestamp\n\n" > "$makefile"
4240 make -f "$makefile"
4241 rm   -f "$makefile"
4242 @end smallexample
4244 Unfortunately although the solution above is quite elegant, it fails
4245 to cope with white space within file names, and adjusting it to do so
4246 would require a rather complex shell script.
4249 @subsection Coping with odd filenames too
4251 We can fix both of these problems (looping and problems with white
4252 space), and do things more efficiently too.  The following command
4253 works with newlines and doesn't need to sort the list of filenames.
4255 @smallexample
4256 find subdir -newer timestamp -printf "%A@@:%p\0" | 
4257    perl -0 newest.pl |
4258    xargs --no-run-if-empty --null -i \
4259       find @{@} -maxdepth 0 -newer timestamp -exec touch -r @{@} timestamp \;
4260 @end smallexample
4262 The first @code{find} command generates a list of files which are
4263 newer than the original timestamp file, and prints a list of them with
4264 their timestamps.  The @file{newest.pl} script simply filters out all
4265 the filenames which have timestamps which are older than whatever the
4266 newest file is:-
4268 @smallexample
4269 @verbatim
4270 #! /usr/bin/perl -0
4271 my @newest = ();
4272 my $latest_stamp = undef;
4273 while (<>) {
4274     my ($stamp, $name) = split(/:/);
4275     if (!defined($latest_stamp) || ($tstamp > $latest_stamp)) {
4276         $latest_stamp = $stamp;
4277         @newest = ();
4278     }
4279     if ($tstamp >= $latest_stamp) {
4280         push @newest, $name;
4281     }
4283 print join("\0", @newest);
4284 @end verbatim
4285 @end smallexample
4287 This prints a list of zero or more files, all of which are newer than
4288 the original timestamp file, and which have the same timestamp as each
4289 other, to the nearest second.  The second @code{find} command takes
4290 each resulting file one at a time, and if that is newer than the
4291 timestamp file, the timestamp is updated.
4293 @node Security Considerations
4294 @chapter Security Considerations
4296 Security considerations are important if you are using @code{find} or
4297 @code{xargs} to search for or process files that don't belong to you
4298 or which other people have control.  Security considerations
4299 relating to @code{locate} may also apply if you have files which you
4300 do not want others to see.
4302 The most severe forms of security problems affecting
4303 @code{find} and related programs are when third parties bring
4304 about a situation allowing them to do something
4305 they would normally not be able to accomplish.  This is called @emph{privilege
4306 elevation}.  This might include deleting files they would not normally
4307 be able to delete.  It is common for the operating system to periodically
4308 invoke @code{find} for self-maintenance purposes.  These invocations of
4309 @code{find} are particularly problematic from a security point of view
4310 as these are often invoked by the superuser and search the entire
4311 filesystem hierarchy.  Generally, the severity of any associated problem depends
4312 on what the system is going to do with the files found by @code{find}.
4314 @menu
4315 * Levels of Risk::      What is your level of exposure to security problems?
4316 * Security Considerations for find::  Security problems with find
4317 * Security Considerations for xargs:: Security problems with xargs
4318 * Security Considerations for locate:: Security problems with locate
4319 * Security Summary:: That was all very complex, what does it boil down to?
4320 @end menu
4323 @node Levels of Risk
4324 @section Levels of Risk
4326 There are some security risks inherent in the use of @code{find},
4327 @code{xargs} and (to a lesser extent) @code{locate}.  The severity of
4328 these risks depends on what sort of system you are using:
4330 @table @strong
4331 @item High risk
4332 Multi-user systems where you do not control (or trust) the other
4333 users, and on which you execute @code{find}, including areas where
4334 those other users can manipulate the filesystem (for example beneath
4335 @file{/home} or @file{/tmp}).
4337 @item Medium Risk
4338 Systems where the actions of other users can create file names chosen
4339 by them, but to which they don't have access while @code{find} is
4340 being run.  This access might include leaving programs running (shell
4341 background jobs, @code{at} or @code{cron} tasks, for example).  On
4342 these sorts of systems, carefully written commands (avoiding use of
4343 @samp{-print} for example) should not expose you to a high degree of
4344 risk.  Most systems fall into this category.
4346 @item Low Risk
4347 Systems to which untrusted parties do not have access, cannot create
4348 file names of their own choice (even remotely) and which contain no
4349 security flaws which might enable an untrusted third party to gain
4350 access.  Most systems do not fall into this category because there are
4351 many ways in which external parties can affect the names of files that
4352 are created on your system.  The system on which I am writing this for
4353 example automatically downloads software updates from the Internet;
4354 the names of the files in which these updates exist are chosen by
4355 third parties@footnote{Of course, I trust these parties to a large
4356 extent anyway, because I install software provided by them; I choose
4357 to trust them in this way, and that's a deliberate choice}.
4358 @end table
4360 In the discussion above, ``risk'' denotes the likelihood that someone
4361 can cause @code{find}, @code{xargs}, @code{locate} or some other
4362 program which is controlled by them to do something you did not
4363 intend.  The levels of risk suggested do not take any account of the
4364 consequences of this sort of event.  That is, if you operate a ``low
4365 risk'' type system, but the consequences of a security problem are
4366 disastrous, then you should still give serious thought to all the
4367 possible security problems, many of which of course will not be
4368 discussed here -- this section of the manual is intended to be
4369 informative but not comprehensive or exhaustive.
4371 If you are responsible for the operation of a system where the
4372 consequences of a security problem could be very important, you should
4373 do two things:-
4375 @enumerate
4376 @item Define a security policy which defines who is allowed to do what
4377 on your system.
4378 @item Seek competent advice on how to enforce your policy, detect
4379 breaches of that policy, and take account of any potential problems
4380 that might fall outside the scope of your policy.
4381 @end enumerate
4384 @node Security Considerations for find
4385 @section Security Considerations for @code{find}
4388 Some of the actions @code{find} might take have a direct effect;
4389 these include @code{-exec} and @code{-delete}.  However, it is also
4390 common to use @code{-print} explicitly or implicitly, and so if
4391 @code{find} produces the wrong list of file names, that can also be a
4392 security problem; consider the case for example where @code{find} is
4393 producing a list of files to be deleted.
4395 We normally assume that the @code{find} command line expresses the
4396 file selection criteria and actions that the user had in mind -- that
4397 is, the command line is ``trusted'' data.
4399 From a security analysis point of view, the output of @code{find}
4400 should be correct; that is, the output should contain only the names
4401 of those files which meet the user's criteria specified on the command
4402 line.  This applies for the @code{-exec} and @code{-delete} actions;
4403 one can consider these to be part of the output.
4405 On the other hand, the contents of the filesystem can be manipulated
4406 by other people, and hence we regard this as ``untrusted'' data.  This
4407 implies that the @code{find} command line is a filter which converts
4408 the untrusted contents of the filesystem into a correct list of output
4409 files.
4411 The filesystem will in general change while @code{find} is searching
4412 it; in fact, most of the potential security problems with @code{find}
4413 relate to this issue in some way.
4415 @dfn{Race conditions} are a general class of security problem where the
4416 relative ordering of actions taken by @code{find} (for example) and
4417 something else are critically important in getting the correct and expected result@footnote{This is more or less the
4418 definition of the term ``race condition''} .
4420 For @code{find}, an attacker might move or rename files or directories in
4421 the hope that an action might be taken against a file which was not
4422 normally intended to be affected.  Alternatively, this sort of attack
4423 might be intended to persuade @code{find} to search part of the
4424 filesystem which would not normally be included in the search
4425 (defeating the @code{-prune} action for example).
4427 @menu
4428 * Problems with -exec and filenames::
4429 * Changing the Current Working Directory::
4430 * Race Conditions with -exec::
4431 * Race Conditions with -print and -print0::
4432 @end menu
4434 @node Problems with -exec and filenames
4435 @subsection Problems with -exec and filenames
4437 It is safe in many cases to use the @samp{-execdir} action with any
4438 file name.  Because @samp{-execdir} prefixes the arguments it passes
4439 to programs with @samp{./}, you will not accidentally pass an argument
4440 which is interpreted as an option.  For example the file @file{-f}
4441 would be passed to @code{rm} as @file{./-f}, which is harmless.
4443 However, your degree of safety does depend on the nature of the
4444 program you are running.  For example constructs such as these two commands
4446 @example
4447 # risky
4448 find -exec sh -c "something @{@}" \;
4449 find -execdir sh -c "something @{@}" \;
4450 @end example
4452 are very dangerous.  The reason for this is that the @samp{@{@}} is
4453 expanded to a filename which might contain a semicolon or other
4454 characters special to the shell.  If for example someone creates the
4455 file @file{/tmp/foo; rm -rf $HOME} then the two commands above could
4456 delete someone's home directory.
4458 So for this reason do not run any command which will pass untrusted
4459 data (such as the names of files) to commands which interpret
4460 arguments as commands to be further interpreted (for example
4461 @samp{sh}).
4463 In the case of the shell, there is a clever workaround for this
4464 problem:
4466 @example
4467 # safer 
4468 find -exec sh -c 'something "$@@"' @{@} \;
4469 find -execdir sh -c 'something "$@@"' @{@}\;
4470 @end example
4472 This approach is not guaranteed to avoid every problem, but it is much
4473 safer than substituting data of an attacker's choice into the text of
4474 a shell command.
4476 @node Changing the Current Working Directory
4477 @subsection Changing the Current Working Directory
4479 As @code{find} searches the filesystem, it finds subdirectories and
4480 then searches within them by changing its working directory.  First,
4481 @code{find} reaches and recognises a subdirectory.  It then decides if that
4482 subdirectory meets the criteria for being searched; that is, any
4483 @samp{-xdev} or @samp{-prune} expressions are taken into account.  The
4484 @code{find} program will then change working directory and proceed to
4485 search the directory.
4487 A race condition attack might take the form that once the checks
4488 relevant to @samp{-xdev} and @samp{-prune} have been done, an attacker
4489 might rename the directory that was being considered, and put in its
4490 place a symbolic link that actually points somewhere else.
4492 The idea behind this attack is to fool @code{find} into going into the
4493 wrong directory.  This would leave @code{find} with a working
4494 directory chosen by an attacker, bypassing any protection apparently
4495 provided by @samp{-xdev} and @samp{-prune}, and any protection
4496 provided by being able to @emph{not} list particular directories on
4497 the @code{find} command line.  This form of attack is particularly
4498 problematic if the attacker can predict when the @code{find} command
4499 will be run, as is the case with @code{cron} tasks for example.
4501 GNU @code{find} has specific safeguards to prevent this general class
4502 of problem.  The exact form of these safeguards depends on the
4503 properties of your system.
4505 @menu
4506 * O_NOFOLLOW::                     Safely changing directory using fchdir().
4507 * Systems without O_NOFOLLOW::     Checking for symbolic links after chdir().
4508 @end menu
4510 @node O_NOFOLLOW
4511 @subsubsection O_NOFOLLOW
4513 If your system supports the O_NOFOLLOW flag @footnote{GNU/Linux
4514 (kernel version 2.1.126 and later) and FreeBSD (3.0-CURRENT and later)
4515 support this} to the @code{open(2)} system call, @code{find} uses it
4516 when safely changing directory.  The target directory is first opened
4517 and then @code{find} changes working directory with the
4518 @code{fchdir()} system call.  This ensures that symbolic links are not
4519 followed, preventing the sort of race condition attack in which use
4520 is made of symbolic links.
4522 If for any reason this approach does not work, @code{find} will fall
4523 back on the method which is normally used if O_NOFOLLOW is not
4524 supported.
4526 You can tell if your system supports O_NOFOLLOW by running
4528 @example
4529 find --version
4530 @end example
4532 This will tell you the version number and which features are enabled.
4533 For example, if I run this on my system now, this gives:
4534 @example
4535 GNU find version 4.2.18-CVS
4536 Features enabled: D_TYPE O_NOFOLLOW(enabled)
4537 @end example
4539 Here, you can see that I am running a version of @code{find} which was
4540 built from the development (CVS) code prior to the release of
4541 findutils-4.2.18, and that the D_TYPE and O_NOFOLLOW features are
4542 present.  O_NOFOLLOW is qualified with ``enabled''.  This simply means
4543 that the current system seems to support O_NOFOLLOW.  This check is
4544 needed because it is possible to build @code{find} on a system that
4545 defines O_NOFOLLOW and then run it on a system that ignores the
4546 O_NOFOLLOW flag.  We try to detect such cases at startup by checking
4547 the operating system and version number; when this happens you will
4548 see ``O_NOFOLLOW(disabled)'' instead.
4550 @node Systems without O_NOFOLLOW
4551 @subsubsection Systems without O_NOFOLLOW
4553 The strategy for preventing this type of problem on systems that lack
4554 support for the O_NOFOLLOW flag is more complex.  Each time
4555 @code{find} changes directory, it examines the directory it is about
4556 to move to, issues the @code{chdir()} system call, and then checks
4557 that it has ended up in the subdirectory it expected.  If all is as
4558 expected, processing continues as normal.  However, there are two main
4559 reasons why the directory might change: the use of an automounter and
4560 the someone removing the old directory and replacing it with something
4561 else while @code{find} is trying to descend into it.
4563 Where a filesystem ``automounter'' is in use it can be the case that
4564 the use of the @code{chdir()} system call can itself cause a new
4565 filesystem to be mounted at that point.  On systems that do not
4566 support O_NOFOLLOW, this will cause @code{find}'s security check to
4567 fail.
4569 However, this does not normally represent a security problem, since
4570 the automounter configuration is normally set up by the system
4571 administrator.  Therefore, if the @code{chdir()} sanity check fails,
4572 @code{find} will make one more attempt@footnote{This may not be the
4573 case for the fts-based executable}.  If that succeeds, execution
4574 carries on as normal.  This is the usual case for automounters.
4576 Where an attacker is trying to exploit a race condition, the problem
4577 may not have gone away on the second attempt.  If this is the case,
4578 @code{find} will issue a warning message and then ignore that
4579 subdirectory.  When this happens, actions such as @samp{-exec} or
4580 @samp{-print} may already have taken place for the problematic
4581 subdirectory.  This is because @code{find} applies tests and actions
4582 to directories before searching within them (unless @samp{-depth} was
4583 specified).
4585 Because of the nature of the directory-change operation and security
4586 check, in the worst case the only things that @code{find} would have
4587 done with the directory are to move into it and back out to the
4588 original parent.  No operations would have been performed within that
4589 directory.
4591 @node Race Conditions with -exec
4592 @subsection Race Conditions with -exec
4594 The @samp{-exec} action causes another program to be run.  It passes
4595 to the program the name of the file which is being considered at the
4596 time.  The invoked program will typically then perform some action
4597 on that file.  Once again, there is a race condition which can be
4598 exploited here.  We shall take as a specific example the command
4600 @example
4601 find /tmp -path /tmp/umsp/passwd -exec /bin/rm
4602 @end example
4604 In this simple example, we are identifying just one file to be deleted
4605 and invoking @code{/bin/rm} to delete it.  A problem exists because
4606 there is a time gap between the point where @code{find} decides that
4607 it needs to process the @samp{-exec} action and the point where the
4608 @code{/bin/rm} command actually issues the @code{unlink()} system
4609 call to delete the file from the filesystem.  Within this time period, an attacker can rename the
4610 @file{/tmp/umsp} directory, replacing it with a symbolic link to
4611 @file{/etc}.  There is no way for @code{/bin/rm} to determine that it
4612 is working on the same file that @code{find} had in mind.  Once the
4613 symbolic link is in place, the attacker has persuaded @code{find} to
4614 cause the deletion of the @file{/etc/passwd} file, which is not the
4615 effect intended by the command which was actually invoked.
4617 One possible defence against this type of attack is to modify the
4618 behaviour of @samp{-exec} so that the @code{/bin/rm} command is run
4619 with the argument @file{./passwd} and a suitable choice of working
4620 directory.  This would allow the normal sanity check that @code{find}
4621 performs to protect against this form of attack too.  Unfortunately,
4622 this strategy cannot be used as the POSIX standard specifies that the
4623 current working directory for commands invoked with @samp{-exec} must
4624 be the same as the current working directory from which @code{find}
4625 was invoked.  This means that the @samp{-exec} action is inherently
4626 insecure and can't be fixed.
4628 GNU @code{find} implements a more secure variant of the @samp{-exec}
4629 action, @samp{-execdir}.  The @samp{-execdir} action
4630 ensures that it is not necessary to dereference subdirectories to
4631 process target files.  The current directory used to invoke programs
4632 is the same as the directory in which the file to be processed exists
4633 (@file{/tmp/umsp} in our example, and only the basename of the file to
4634 be processed is passed to the invoked command, with a @samp{./}
4635 prepended (giving @file{./passwd} in our example).
4637 The @samp{-execdir} action refuses to do anything if the current
4638 directory is included in the @var{$PATH} environment variable.  This
4639 is necessary because @samp{-execdir} runs programs in the same
4640 directory in which it finds files -- in general, such a directory
4641 might be writable by untrusted users.  For similar reasons,
4642 @samp{-execdir} does not allow @samp{@{@}} to appear in the name of
4643 the command to be run.
4645 @node Race Conditions with -print and -print0
4646 @subsection Race Conditions with -print and -print0
4648 The @samp{-print} and @samp{-print0} actions can be used to produce a
4649 list of files matching some criteria, which can then be used with some
4650 other command, perhaps with @code{xargs}.  Unfortunately, this means
4651 that there is an unavoidable time gap between @code{find} deciding
4652 that one or more files meet its criteria and the relevant command
4653 being executed.  For this reason, the @samp{-print} and @samp{-print0}
4654 actions are just as insecure as @samp{-exec}.
4656 In fact, since the construction
4658 @example
4659 find @dots{}  -print | xargs @enddots{}
4660 @end example
4662 does not cope correctly with newlines or other ``white space'' in
4663 file names, and copes poorly with file names containing quotes, the
4664 @samp{-print} action is less secure even than @samp{-print0}.
4667 @comment  node-name,  next,  previous,  up
4668 @comment @node Security Considerations for xargs
4669 @node Security Considerations for xargs
4670 @section Security Considerations for @code{xargs}
4672 The description of the race conditions affecting the @samp{-print}
4673 action of @code{find} shows that @code{xargs} cannot be secure if it
4674 is possible for an attacker to modify a filesystem after @code{find}
4675 has started but before @code{xargs} has completed all its actions.
4677 However, there are other security issues that exist even if it is not
4678 possible for an attacker to have access to the filesystem in real
4679 time.  Firstly, if it is possible for an attacker to create files with
4680 names of their choice on the filesystem, then @code{xargs} is
4681 insecure unless the @samp{-0} option is used.  If a file with the name
4682 @file{/home/someuser/foo/bar\n/etc/passwd} exists (assume that
4683 @samp{\n} stands for a newline character), then @code{find @dots{} -print}
4684 can be persuaded to print three separate lines:
4686 @example
4687 /home/someuser/foo/bar
4689 /etc/passwd
4690 @end example
4692 If it finds a blank line in the input, @code{xargs} will ignore it.
4693 Therefore, if some action is to be taken on the basis of this list of
4694 files, the @file{/etc/passwd} file would be included even if this was
4695 not the intent of the person running find.  There are circumstances in
4696 which an attacker can use this to their advantage.  The same
4697 consideration applies to file names containing ordinary spaces rather
4698 than newlines, except that of course the list of file names will no
4699 longer contain an ``extra'' newline.
4701 This problem is an unavoidable consequence of the default behaviour of
4702 the @code{xargs} command, which is specified by the POSIX standard.
4703 The only ways to avoid this problem are either to avoid all use of
4704 @code{xargs} in favour for example of @samp{find -exec} or (where
4705 available) @samp{find -execdir}, or to use the @samp{-0} option, which
4706 ensures that @code{xargs} considers file names to be separated by
4707 ASCII NUL characters rather than whitespace.  However, useful as this
4708 option is, the POSIX standard does not make it mandatory.
4710 POSIX also specifies that @code{xargs} interprets quoting and trailing
4711 whitespace specially in filenames, too.  This means that using
4712 @code{find ... -print | xargs ...} can cause the commands run by
4713 @code{xargs} to receive a list of file names which is not the same as
4714 the list printed by @code{find}.   The interpretation of quotes and
4715 trailing whitespace is turned off by the @samp{-0} argument to
4716 @code{xargs}, which is another reason to use that option.
4718 @comment  node-name,  next,  previous,  up
4719 @node Security Considerations for locate
4720 @section Security Considerations for @code{locate}
4722 It is fairly unusual for the output of @code{locate} to be fed into
4723 another command.  However, if this were to be done, this would raise
4724 the same set of security issues as the use of @samp{find @dots{} -print}.
4725 Although the problems relating to whitespace in file names can be
4726 resolved by using @code{locate}'s @samp{-0} option, this still leaves
4727 the race condition problems associated with @samp{find @dots{} -print0}.
4728 There is no way to avoid these problems in the case of @code{locate}.
4730 @node Security Summary
4731 @section Summary
4733 Where untrusted parties can create files on the system, or affect the
4734 names of files that are created, all uses for @code{find},
4735 @code{locate} and @code{xargs} have known security problems except the
4736 following:
4738 @table @asis
4739 @item Informational use only
4740 Uses where the programs are used to prepare lists of file names upon
4741 which no further action will ever be taken.
4743 @item @samp{-delete}
4744 Use of the @samp{-delete} action with @code{find} to delete files
4745 which meet specified criteria
4747 @item @samp{-execdir}
4748 Use of the @samp{-execdir} action with @code{find} where the
4749 @env{PATH} environment variable contains directories which contain
4750 only trusted programs.
4751 @end table
4753 @comment  node-name,  next,  previous,  up
4754 @node Error Messages
4755 @chapter Error Messages
4757 This section describes some of the error messages sometimes made by
4758 @code{find}, @code{xargs}, or @code{locate}, explains them and in some
4759 cases provides advice as to what you should do about this.
4761 This manual is written in English.  The GNU findutils software
4762 features translations of error messages for many languages.  For this
4763 reason the error messages produced by the programs are made to be as
4764 self-explanatory as possible.  This approach avoids leaving people to
4765 figure out which test an English-language error message corresponds
4766 to.  Error messages which are self-explanatory will not normally be
4767 mentioned in this document.  For those messages mentioned in this
4768 document, only the English-language version of the message will be
4769 listed.
4771 @menu
4772 * Error Messages From find::
4773 * Error Messages From xargs::
4774 * Error Messages From locate::
4775 * Error Messages From updatedb::
4776 @end menu
4778 @node Error Messages From find
4779 @section Error Messages From @code{find}
4781 Most error messages produced by find are self-explanatory.  Error
4782 messages sometimes include a filename.  When this happens, the
4783 filename is quoted in order to prevent any unusual characters in the
4784 filename making unwanted changes in the state of the terminal.
4786 @table @samp
4787 @item invalid predicate `-foo'
4788 This means that the @code{find} command line included something that
4789 started with a dash or other special character.  The @code{find}
4790 program tried to interpret this as a test, action or option, but
4791 didn't recognise it.  If it was intended to be a test, check what was
4792 specified against the documentation.  If, on the other hand, the
4793 string is the name of a file which has been expanded from a wildcard
4794 (for example because you have a @samp{*} on the command line),
4795 consider using @samp{./*} or just @samp{.} instead.
4797 @item unexpected extra predicate
4798 This usually happens if you have an extra bracket on the command line
4799 (for example @samp{find . -print \)}).
4801 @item Warning: filesystem /path/foo has recently been mounted
4802 @itemx Warning: filesystem /path/foo has recently been unmounted
4803 These messages might appear when @code{find} moves into a directory
4804 and finds that the device number and inode are different to what it
4805 expected them to be.  If the directory @code{find} has moved into is
4806 on an network filesystem (NFS), it will not issue this message, because
4807 @code{automount} frequently mounts new filesystems on directories as
4808 you move into them (that is how it knows you want to use the
4809 filesystem).  So, if you do see this message, be wary ---
4810 @code{automount} may not have been responsible.  Consider the
4811 possibility that someone else is manipulating the filesystem while
4812 @code{find} is running.  Some people might do this in order to mislead
4813 @code{find} or persuade it to look at one set of files when it thought
4814 it was looking at another set.
4816 @item /path/foo changed during execution of find (old device number 12345, new device number 6789, filesystem type is <whatever>) [ref XXX]
4817 This message is issued when @code{find} moves into a directory and ends up
4818 somewhere it didn't expect to be.  This happens in one of two
4819 circumstances.  Firstly, this happens when @code{automount} intervenes
4820 on a system where @code{find} doesn't know how to determine what
4821 the current set of mounted filesystems is.
4823 Secondly, this can happen when the device number of a directory
4824 appears to change during a change of current directory, but
4825 @code{find} is moving up the filesystem hierarchy rather than down into it.
4826 In order to prevent @code{find} wandering off into some unexpected
4827 part of the filesystem, we stop it at this point.
4829 @item Don't know how to use getmntent() to read `/etc/mtab'.  This is a bug.
4830 This message is issued when a problem similar to the above occurs on a
4831 system where @code{find} doesn't know how to figure out the current
4832 list of mount points.  Ask for help on @email{bug-findutils@@gnu.org}.
4834 @item /path/foo/bar changed during execution of find (old inode number 12345, new inode number 67893, filesystem type is <whatever>) [ref XXX]"),
4835 This message is issued when @code{find} moves into a directory and
4836 discovers that the inode number of that directory
4837 is different from the inode number that it obtained when it examined the
4838 directory previously.  This usually means that while
4839 @code{find} was deep in a directory hierarchy doing a
4840 time consuming operation, somebody has moved one of the parent directories to
4841 another location in the same filesystem.  This may or may not have been done
4842 maliciously.  In any case, @code{find} stops at this point
4843 to avoid traversing parts of the filesystem that it wasn't
4844 intended.  You can use @code{ls -li} or @code{find /path -inum
4845 12345 -o -inum 67893} to find out more about what has happened.
4847 @item sanity check of the fnmatch() library function failed.
4848 Please submit a bug report.  You may well be asked questions about
4849 your system, and if you compiled the @code{findutils} code yourself,
4850 you should keep your copy of the build tree around.  The likely
4851 explanation is that your system has a buggy implementation of
4852 @code{fnmatch} that looks enough like the GNU version to fool
4853 @code{configure}, but which doesn't work properly.
4855 @item cannot fork
4856 This normally happens if you use the @code{-exec} action or
4857 something similar (@code{-ok} and so forth) but the system has run out
4858 of free process slots.  This is either because the system is very busy
4859 and the system has reached its maximum process limit, or because you
4860 have a resource limit in place and you've reached it.  Check the
4861 system for runaway processes (with @code{ps}, if possible).  Some process
4862 slots are normally reserved for use by @samp{root}.
4864 @item some-program terminated by signal 99
4865 Some program which was launched with @code{-exec} or similar was killed
4866 with a fatal signal.  This is just an advisory message.
4867 @end table
4870 @node Error Messages From xargs
4871 @section Error Messages From xargs
4873 @table @samp
4874 @item environment is too large for exec
4875 This message means that you have so many environment variables set (or
4876 such large values for them) that there is no room within the
4877 system-imposed limits on program command line argument length to
4878 invoke any program.  This is an unlikely situation and is more likely
4879 result of an attempt to test the limits of @code{xargs}, or break it.
4880 Please try unsetting some environment variables, or exiting the
4881 current shell.  You can also use @samp{xargs --show-limits} to
4882 understand the relevant sizes.
4884 @item can not fit single argument within argument list size limit
4885 You are using the @samp{-I} option and @code{xargs} doesn't have
4886 enough space to build a command line because it has read a really
4887 large item and it doesn't fit.  You can probably work around this
4888 problem with the @samp{-s} option, but the default size is pretty
4889 large.  This is a rare situation and is more likely an attempt to test
4890 the limits of @code{xargs}, or break it.  Otherwise, you will need to
4891 try to shorten the problematic argument or not use @code{xargs}.
4893 @item cannot fork
4894 See the description of the similar message for @code{find}.
4896 @item <program>: exited with status 255; aborting
4897 When a command run by @code{xargs} exits with status 255, @code{xargs}
4898 is supposed to stop.  If this is not what you intended, wrap the
4899 program you are trying to invoke in a shell script which doesn't
4900 return status 255.
4902 @item <program>: terminated by signal 99
4903 See the description of the similar message for @code{find}.
4904 @end table
4906 @node Error Messages From locate
4907 @section Error Messages From @code{locate}
4909 @table @samp
4910 @item warning: database @file{@value{LOCATE_DB}} is more than 8 days old
4911 The @code{locate} program relies on a database which is periodically
4912 built by the @code{updatedb} program.  That hasn't happened in a long
4913 time.  To fix this problem, run @code{updatedb} manually.  This can
4914 often happen on systems that are generally not left on, so the
4915 periodic ``cron'' task which normally does this doesn't get a chance
4916 to run.
4918 @item locate database @file{@value{LOCATE_DB}} is corrupt or invalid
4919 This should not happen.  Re-run @code{updatedb}.  If that works, but
4920 @code{locate} still produces this error, run @code{locate --version}
4921 and @code{updatedb --version}.  These should produce the same output.
4922 If not, you are using a mixed toolset; check your @samp{$PATH}
4923 environment variable and your shell aliases (if you have any).  If
4924 both programs claim to be GNU versions, this is a bug; all versions of
4925 these programs should interoperate without problem.  Ask for help on
4926 @email{bug-findutils@@gnu.org}.
4927 @end table
4930 @node Error Messages From updatedb
4931 @section Error Messages From updatedb
4933 The @code{updatedb} program (and the programs it invokes) do issue
4934 error messages, but none seem to be candidates for guidance.  If
4935 you are having a problem understanding one of these, ask for help on
4936 @email{bug-findutils@@gnu.org}.
4939 @node Primary Index
4940 @unnumbered @code{find} Primary Index
4942 This is a list of all of the primaries (tests, actions, and options)
4943 that make up @code{find} expressions for selecting files.  @xref{find
4944 Expressions}, for more information on expressions.
4946 @printindex fn
4948 @bye
4950 @comment texi related words used by Emacs' spell checker ispell.el
4952 @comment LocalWords: texinfo setfilename settitle setchapternewpage
4953 @comment LocalWords: iftex finalout ifinfo DIR titlepage vskip pt
4954 @comment LocalWords: filll dir samp dfn noindent xref pxref
4955 @comment LocalWords: var deffn texi deffnx itemx emph asis
4956 @comment LocalWords: findex smallexample subsubsection cindex
4957 @comment LocalWords: dircategory direntry itemize
4959 @comment other words used by Emacs' spell checker ispell.el
4960 @comment LocalWords: README fred updatedb xargs Plett Rendell akefile
4961 @comment LocalWords: args grep Filesystems fo foo fOo wildcards iname
4962 @comment LocalWords: ipath regex iregex expr fubar regexps
4963 @comment LocalWords: metacharacters macs sr sc inode lname ilname
4964 @comment LocalWords: sysdep noleaf ls inum xdev filesystems usr atime
4965 @comment LocalWords: ctime mtime amin cmin mmin al daystart Sladkey rm
4966 @comment LocalWords: anewer cnewer bckw rf xtype uname gname uid gid
4967 @comment LocalWords: nouser nogroup chown chgrp perm ch maxdepth
4968 @comment LocalWords: mindepth cpio src CD AFS statted stat fstype ufs
4969 @comment LocalWords: nfs tmp mfs printf fprint dils rw djm Nov lwall
4970 @comment LocalWords: POSIXLY fls fprintf strftime locale's EDT GMT AP
4971 @comment LocalWords: EST diff perl backquotes sprintf Falstad Oct cron
4972 @comment LocalWords: eg vmunix mkdir afs allexec allwrite ARG bigram
4973 @comment LocalWords: bigrams cd chmod comp crc CVS dbfile dum eof
4974 @comment LocalWords: fileserver filesystem fn frcode Ghazi Hnewc iXX
4975 @comment LocalWords: joeuser Kaveh localpaths localuser LOGNAME
4976 @comment LocalWords: Meyering mv netpaths netuser nonblank nonblanks
4977 @comment LocalWords: ois ok Pinard printindex proc procs prunefs
4978 @comment LocalWords: prunepaths pwd RFS rmadillo rmdir rsh sbins str
4979 @comment LocalWords: su Timar ubins ug unstripped vf VM Weitzel
4980 @comment LocalWords: wildcard zlogout basename execdir wholename iwholename
4981 @comment LocalWords: timestamp timestamps Solaris FreeBSD OpenBSD POSIX