Support fts() in FTS_CWDFD mode. Also work around Savannah bug #18466 (with a perfor...
[findutils.git] / doc / find.texi
blob66252797d847c6add2ac08fac900d5471412ec29
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
11 @iftex
12 @finalout
13 @end iftex
15 @dircategory Basics
16 @direntry
17 * Finding files: (find).        Operating on files matching certain criteria.
18 @end direntry
20 @dircategory Individual utilities
21 @direntry
22 * find: (find)Invoking find.                    Finding and acting on files.
23 * locate: (find)Invoking locate.                Finding files in a database.
24 * updatedb: (find)Invoking updatedb.            Building the locate database.
25 * xargs: (find)Invoking xargs.                  Operating on many files.
26 @end direntry
28 @copying
30 This file documents the GNU utilities for finding files that match
31 certain criteria and performing various operations on them.
33 Copyright (C) 1994, 1996, 1998, 2000, 2001, 2003, 2004, 2005 Free
34 Software Foundation, Inc.
36 Permission is granted to make and distribute verbatim copies of
37 this manual provided the copyright notice and this permission notice
38 are preserved on all copies.
40 @ignore
41 Permission is granted to process this file through TeX and print the
42 results, provided the printed document carries copying permission
43 notice identical to this one except for the removal of this paragraph
44 (this paragraph not being relevant to the printed manual).
46 @end ignore
47 Permission is granted to copy and distribute modified versions of this
48 manual under the conditions for verbatim copying, provided that the
49 entire resulting derived work is distributed under the terms of a
50 permission notice identical to this one.
52 Permission is granted to copy and distribute translations of this
53 manual into another language, under the above conditions for modified
54 versions, except that this permission notice may be stated in a
55 translation approved by the Foundation.
56 @end copying
58 @titlepage
59 @title Finding Files
60 @subtitle Edition @value{EDITION}, for GNU @code{find} version @value{VERSION}
61 @subtitle @value{UPDATED}
62 @author by David MacKenzie and James Youngman
64 @page
65 @vskip 0pt plus 1filll
66 @insertcopying{}
67 @end titlepage
69 @contents
71 @ifnottex
72 @node Top
73 @top GNU Findutils
74 @comment  node-name,  next,  previous,  up
76 This file documents the GNU utilities for finding files that match
77 certain criteria and performing various actions on them.
79 This is edition @value{EDITION}, for @code{find} version @value{VERSION}.
80 @end ifnottex
82 @c The master menu, created with texinfo-master-menu, goes here.
84 @menu
85 * Introduction::                Summary of the tasks this manual describes.
86 * Finding Files::               Finding files that match certain criteria.
87 * Actions::                     Doing things to files you have found.
88 * Databases::                   Maintaining file name databases.
89 * File Permissions::            How to control access to files.
90 * Date input formats::          Specifying literal times.
91 * Reference::                   Summary of how to invoke the programs.
92 * Common Tasks::                Solutions to common real-world problems.
93 * Worked Examples::             Examples demonstrating more complex points.
94 * Security Considerations::     Security issues relating to findutils.
95 * Error Messages::              Explanations of some messages you might see.
96 * Primary Index::               The components of @code{find} expressions.
97 @end menu
99 @node Introduction
100 @chapter Introduction
102 This manual shows how to find files that meet criteria you specify,
103 and how to perform various actions on the files that you find.  The
104 principal programs that you use to perform these tasks are
105 @code{find}, @code{locate}, and @code{xargs}.  Some of the examples in
106 this manual use capabilities specific to the GNU versions of those
107 programs.
109 GNU @code{find} was originally written by Eric Decker, with
110 enhancements by David MacKenzie, Jay Plett, and Tim Wood.  GNU
111 @code{xargs} was originally written by Mike Rendell, with enhancements
112 by David MacKenzie.  GNU @code{locate} and its associated utilities
113 were originally written by James Woods, with enhancements by David
114 MacKenzie.  The idea for @samp{find -print0} and @samp{xargs -0} came
115 from Dan Bernstein.  The current maintainer of GNU findutils (and this
116 manual) is James Youngman.  Many other people have contributed bug
117 fixes, small improvements, and helpful suggestions.  Thanks!
119 To report a bug in GNU findutils, please use the form on the Savannah
120 web site at
121 @code{http://savannah.gnu.org/bugs/?group=findutils}.  Reporting bugs
122 this way means that you will then be able to track progress in fixing
123 the problem.  
125 If you don't have web access, you can also just send mail to the
126 mailing list.  The mailing list @email{bug-findutils@@gnu.org} carries
127 discussion of bugs in findutils, questions and answers about the
128 software and discussion of the development of the programs.  To join
129 the list, send email to @email{bug-findutils-request@@gnu.org}.
131 Please read any relevant sections of this manual before asking for
132 help on the mailing list.  You may also find it helpful to read the
133 NON-BUGS section of the @code{find} manual page.
135 If you ask for help on the mailing list, people will be able to help
136 you much more effectively if you include the following things:
138 @itemize @bullet
139 @item The version of the software you are running.  You can find this
140 out by running @samp{locate --version}.
141 @item What you were trying to do
142 @item The @emph{exact} command line you used
143 @item The @emph{exact} output you got (if this is very long, try to
144 find a smaller example which exhibits the same problem)
145 @item The output you expected to get
146 @end itemize
148 @menu
149 * Scope::
150 * Overview::
151 * find Expressions::
152 @end menu
154 @node Scope
155 @section Scope
157 For brevity, the word @dfn{file} in this manual means a regular file,
158 a directory, a symbolic link, or any other kind of node that has a
159 directory entry.  A directory entry is also called a @dfn{file name}.
160 A file name may contain some, all, or none of the directories in a
161 path that leads to the file.  These are all examples of what this
162 manual calls ``file names'':
164 @example
165 parser.c
166 README
167 ./budget/may-94.sc
168 fred/.cshrc
169 /usr/local/include/termcap.h
170 @end example
172 A @dfn{directory tree} is a directory and the files it contains, all
173 of its subdirectories and the files they contain, etc.  It can also be
174 a single non-directory file.
176 These programs enable you to find the files in one or more directory
177 trees that:
179 @itemize @bullet
180 @item
181 have names that contain certain text or match a certain pattern;
182 @item
183 are links to certain files;
184 @item
185 were last used during a certain period of time;
186 @item
187 are within a certain size range;
188 @item
189 are of a certain type (regular file, directory, symbolic link, etc.);
190 @item
191 are owned by a certain user or group;
192 @item
193 have certain access permissions or special mode bits;
194 @item
195 contain text that matches a certain pattern;
196 @item
197 are within a certain depth in the directory tree;
198 @item
199 or some combination of the above.
200 @end itemize
202 Once you have found the files you're looking for (or files that are
203 potentially the ones you're looking for), you can do more to them than
204 simply list their names.  You can get any combination of the files'
205 attributes, or process the files in many ways, either individually or
206 in groups of various sizes.  Actions that you might want to perform on
207 the files you have found include, but are not limited to:
209 @itemize @bullet
210 @item
211 view or edit
212 @item
213 store in an archive
214 @item
215 remove or rename
216 @item
217 change access permissions
218 @item
219 classify into groups
220 @end itemize
222 This manual describes how to perform each of those tasks, and more.
224 @node Overview
225 @section Overview
227 The principal programs used for making lists of files that match given
228 criteria and running commands on them are @code{find}, @code{locate},
229 and @code{xargs}.  An additional command, @code{updatedb}, is used by
230 system administrators to create databases for @code{locate} to use.
232 @code{find} searches for files in a directory hierarchy and prints
233 information about the files it found.  It is run like this:
235 @example
236 find @r{[}@var{file}@dots{}@r{]} @r{[}@var{expression}@r{]}
237 @end example
239 @noindent
240 Here is a typical use of @code{find}.  This example prints the names
241 of all files in the directory tree rooted in @file{/usr/src} whose
242 name ends with @samp{.c} and that are larger than 100 Kilobytes.
243 @example
244 find /usr/src -name '*.c' -size +100k -print
245 @end example
247 Notice that the wildcard must be enclosed in quotes in order to
248 protect it from expansion by the shell.
250 @code{locate} searches special file name databases for file names that
251 match patterns.  The system administrator runs the @code{updatedb}
252 program to create the databases.  @code{locate} is run like this:
254 @example
255 locate @r{[}@var{option}@dots{}@r{]} @var{pattern}@dots{}
256 @end example
258 @noindent
259 This example prints the names of all files in the default file name
260 database whose name ends with @samp{Makefile} or @samp{makefile}.
261 Which file names are stored in the database depends on how the system
262 administrator ran @code{updatedb}.
263 @example
264 locate '*[Mm]akefile'
265 @end example
267 The name @code{xargs}, pronounced EX-args, means ``combine
268 arguments.''  @code{xargs} builds and executes command lines by
269 gathering together arguments it reads on the standard input.  Most
270 often, these arguments are lists of file names generated by
271 @code{find}.  @code{xargs} is run like this:
273 @example
274 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
275 @end example
277 @noindent
278 The following command searches the files listed in the file
279 @file{file-list} and prints all of the lines in them that contain the
280 word @samp{typedef}.
281 @example
282 xargs grep typedef < file-list
283 @end example
285 @node find Expressions
286 @section @code{find} Expressions
288 The expression that @code{find} uses to select files consists of one
289 or more @dfn{primaries}, each of which is a separate command line
290 argument to @code{find}.  @code{find} evaluates the expression each
291 time it processes a file.  An expression can contain any of the
292 following types of primaries:
294 @table @dfn
295 @item options
296 affect overall operation rather than the processing of a specific
297 file;
298 @item tests
299 return a true or false value, depending on the file's attributes;
300 @item actions
301 have side effects and return a true or false value; and
302 @item operators
303 connect the other arguments and affect when and whether they are
304 evaluated.
305 @end table
307 You can omit the operator between two primaries; it defaults to
308 @samp{-and}.  @xref{Combining Primaries With Operators}, for ways to
309 connect primaries into more complex expressions.  If the expression
310 contains no actions other than @samp{-prune}, @samp{-print} is
311 performed on all files for which the entire expression is true
312 (@pxref{Print File Name}).
314 Options take effect immediately, rather than being evaluated for each
315 file when their place in the expression is reached.  Therefore, for
316 clarity, it is best to place them at the beginning of the expression.
317 There are two exceptions to this; @samp{-daystart} and @samp{-follow}
318 have different effects depending on where in the command line they
319 appear.  This can be confusing, so it's best to keep them at the
320 beginning, too.
322 Many of the primaries take arguments, which immediately follow them in
323 the next command line argument to @code{find}.  Some arguments are
324 file names, patterns, or other strings; others are numbers.  Numeric
325 arguments can be specified as
327 @table @code
328 @item +@var{n}
329 for greater than @var{n},
330 @item -@var{n}
331 for less than @var{n},
332 @item @var{n}
333 for exactly @var{n}.
334 @end table
336 @node Finding Files
337 @chapter Finding Files
339 By default, @code{find} prints to the standard output the names of the
340 files that match the given criteria.  @xref{Actions}, for how to get
341 more information about the matching files.
344 @menu
345 * Name::
346 * Links::
347 * Time::
348 * Size::
349 * Type::
350 * Owner::
351 * Mode Bits::
352 * Contents::
353 * Directories::
354 * Filesystems::
355 * Combining Primaries With Operators::
356 @end menu
358 @node Name
359 @section Name
361 Here are ways to search for files whose name matches a certain
362 pattern.  @xref{Shell Pattern Matching}, for a description of the
363 @var{pattern} arguments to these tests.
365 Each of these tests has a case-sensitive version and a
366 case-insensitive version, whose name begins with @samp{i}.  In a
367 case-insensitive comparison, the patterns @samp{fo*} and @samp{F??}
368 match the file names @file{Foo}, @samp{FOO}, @samp{foo}, @samp{fOo},
369 etc.
371 @menu
372 * Base Name Patterns::
373 * Full Name Patterns::
374 * Fast Full Name Search::
375 * Shell Pattern Matching::      Wildcards used by these programs.
376 @end menu
378 @node Base Name Patterns
379 @subsection Base Name Patterns
381 @deffn Test -name pattern
382 @deffnx Test -iname pattern
383 True if the base of the file name (the path with the leading
384 directories removed) matches shell pattern @var{pattern}.  For
385 @samp{-iname}, the match is case-insensitive.@footnote{Because we
386 need to perform case-insensitive matching, the GNU fnmatch
387 implementation is always used; if the C library includes the GNU
388 implementation, we use that and otherwise we use the one from gnulib}
389 To ignore a whole directory tree, use @samp{-prune}
390 (@pxref{Directories}).  As an example, to find Texinfo source files in
391 @file{/usr/local/doc}:
393 @example
394 find /usr/local/doc -name '*.texi'
395 @end example
397 Notice that the wildcard must be enclosed in quotes in order to
398 protect it from expansion by the shell.
400 As of findutils version 4.2.2, patterns for @samp{-name} and
401 @samp{-iname} will match a file name with a leading @samp{.}.  For
402 example the command @samp{find /tmp -name \*bar} will match the file
403 @file{/tmp/.foobar}.  Braces within the pattern (@samp{@{@}}) are not
404 considered to be special (that is, @code{find . -name 'foo@{1,2@}'}
405 matches a file named @file{foo@{1,2@}}, not the files @file{foo1} and
406 @file{foo2}.
407 @end deffn
410 @node Full Name Patterns
411 @subsection Full Name Patterns
413 @deffn Test -wholename pattern
414 @deffnx Test -iwholename pattern
415 True if the entire file name, starting with the command line argument
416 under which the file was found, matches shell pattern @var{pattern}.
417 For @samp{-iwholename}, the match is case-insensitive.  To ignore a
418 whole directory tree, use @samp{-prune} rather than checking every
419 file in the tree (@pxref{Directories}).  The ``entire file name'' as
420 used by @code{find} starts with the starting-point specified on the
421 command line, and is not converted to an absolute pathname, so for
422 example @code{cd /; find tmp -wholename /tmp} will never match
423 anything.
424 @end deffn
426 @deffn Test -path pattern
427 @deffnx Test -ipath pattern
428 These tests are deprecated, but work as for @samp{-wholename} and
429 @samp{-iwholename}, respectively.  The @samp{-ipath} test is a GNU
430 extension, but @samp{-path} is also provided by HP-UX @code{find}.
431 @end deffn
433 @deffn Test -regex expr
434 @deffnx Test -iregex expr
435 True if the entire file name matches regular expression @var{expr}.
436 This is a match on the whole path, not a search.  For example, to
437 match a file named @file{./fubar3}, you can use the regular expression
438 @samp{.*bar.} or @samp{.*b.*3}, but not @samp{f.*r3}.  @xref{Regexps,
439 , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}, for a
440 description of the syntax of regular expressions.  For @samp{-iregex},
441 the match is case-insensitive.  There are several varieties of regular
442 expressions; by default this test uses POSIX basic regular
443 expressions, but this can be changed with the option
444 @samp{-regextype}.
445 @end deffn
447 @deffn Option -regextype name
448 This option controls the variety of regular expression syntax
449 understood by the @samp{-regex} and @samp{-iregex} tests.  This option
450 is positional; that is, it only affects regular expressions which
451 occur later in the command line.  If this option is not given, GNU
452 Emacs regular expressions are assumed.  Currently-implemented types
456 @table @samp
457 @item emacs
458 Regular expressions compatible with GNU Emacs; this is also the
459 default behaviour if this option is not used.
460 @item posix-awk
461 Regular expressions compatible with the POSIX awk command (not GNU awk)
462 @item posix-basic
463 POSIX Basic Regular Expressions.
464 @item posix-egrep
465 Regular expressions compatible with the POSIX egrep command
466 @item posix-extended
467 POSIX Extended Regular Expressions
468 @end table
470 @ref{Regular Expressions} for more information on the regular
471 expression dialects understood by GNU findutils.
474 @end deffn
476 @node Fast Full Name Search
477 @subsection Fast Full Name Search
479 To search for files by name without having to actually scan the
480 directories on the disk (which can be slow), you can use the
481 @code{locate} program.  For each shell pattern you give it,
482 @code{locate} searches one or more databases of file names and
483 displays the file names that contain the pattern.  @xref{Shell Pattern
484 Matching}, for details about shell patterns.
486 If a pattern is a plain string---it contains no
487 metacharacters---@code{locate} displays all file names in the database
488 that contain that string.  If a pattern contains
489 metacharacters, @code{locate} only displays file names that match the
490 pattern exactly.  As a result, patterns that contain metacharacters
491 should usually begin with a @samp{*}, and will most often end with one
492 as well.  The exceptions are patterns that are intended to explicitly
493 match the beginning or end of a file name.
495 If you only want @code{locate} to match against the last component of
496 the file names (the ``base name'' of the files) you can use the
497 @samp{--basename} option.  The opposite behaviour is the default, but
498 can be selected explicitly by using the option @samp{--wholename}.
500 The command
501 @example
502 locate @var{pattern}
503 @end example
505 is almost equivalent to
506 @example
507 find @var{directories} -name @var{pattern}
508 @end example
510 where @var{directories} are the directories for which the file name
511 databases contain information.  The differences are that the
512 @code{locate} information might be out of date, and that @code{locate}
513 handles wildcards in the pattern slightly differently than @code{find}
514 (@pxref{Shell Pattern Matching}).
516 The file name databases contain lists of files that were on the system
517 when the databases were last updated.  The system administrator can
518 choose the file name of the default database, the frequency with which
519 the databases are updated, and the directories for which they contain
520 entries.
522 Here is how to select which file name databases @code{locate}
523 searches.  The default is system-dependent.
525 @table @code
526 @item --database=@var{path}
527 @itemx -d @var{path}
528 Instead of searching the default file name database, search the file
529 name databases in @var{path}, which is a colon-separated list of
530 database file names.  You can also use the environment variable
531 @code{LOCATE_PATH} to set the list of database files to search.  The
532 option overrides the environment variable if both are used.
533 @end table
535 @node Shell Pattern Matching
536 @subsection Shell Pattern Matching
538 @code{find} and @code{locate} can compare file names, or parts of file
539 names, to shell patterns.  A @dfn{shell pattern} is a string that may
540 contain the following special characters, which are known as
541 @dfn{wildcards} or @dfn{metacharacters}.
543 You must quote patterns that contain metacharacters to prevent the
544 shell from expanding them itself.  Double and single quotes both work;
545 so does escaping with a backslash.
547 @table @code
548 @item *
549 Matches any zero or more characters.
551 @item ?
552 Matches any one character.
554 @item [@var{string}]
555 Matches exactly one character that is a member of the string
556 @var{string}.  This is called a @dfn{character class}.  As a
557 shorthand, @var{string} may contain ranges, which consist of two
558 characters with a dash between them.  For example, the class
559 @samp{[a-z0-9_]} matches a lowercase letter, a number, or an
560 underscore.  You can negate a class by placing a @samp{!} or @samp{^}
561 immediately after the opening bracket.  Thus, @samp{[^A-Z@@]} matches
562 any character except an uppercase letter or an at sign.
564 @item \
565 Removes the special meaning of the character that follows it.  This
566 works even in character classes.
567 @end table
569 In the @code{find} tests that do shell pattern matching (@samp{-name},
570 @samp{-wholename}, etc.), wildcards in the pattern will match a
571 @samp{.}  at the beginning of a file name.  This is also the case for
572 @code{locate}.  Thus, @samp{find -name '*macs'} will match a file
573 named @file{.emacs}, as will @samp{locate '*macs'}.
575 Slash characters have no special significance in the shell pattern
576 matching that @code{find} and @code{locate} do, unlike in the shell,
577 in which wildcards do not match them.  Therefore, a pattern
578 @samp{foo*bar} can match a file name @samp{foo3/bar}, and a pattern
579 @samp{./sr*sc} can match a file name @samp{./src/misc}.
581 If you want to locate some files with the @samp{locate} command but
582 don't need to see the full list you can use the @samp{--limit} option
583 to see just a small number of results, or the @samp{--count} option to
584 display only the total number of matches.
586 @node Links
587 @section Links
589 There are two ways that files can be linked together.  @dfn{Symbolic
590 links} are a special type of file whose contents are a portion of the
591 name of another file.  @dfn{Hard links} are multiple directory entries
592 for one file; the file names all have the same index node
593 (@dfn{inode}) number on the disk.
595 @menu
596 * Symbolic Links::
597 * Hard Links::
598 @end menu
600 @node Symbolic Links
601 @subsection Symbolic Links
603 Symbolic links are names that reference other files.  GNU @code{find}
604 will handle symbolic links in one of two ways; firstly, it can
605 dereference the links for you - this means that if it comes across a
606 symbolic link, it examines the file that the link points to, in order
607 to see if it matches the criteria you have specified.  Secondly, it
608 can check the link itself in case you might be looking for the actual
609 link.  If the file that the symbolic link points to is also within the
610 directory hierarchy you are searching with the @code{find} command,
611 you may not see a great deal of difference between these two
612 alternatives.
614 By default, @code{find} examines symbolic links themselves when it
615 finds them (and, if it later comes across the linked-to file, it will
616 examine that, too).  If you would prefer @code{find} to dereference
617 the links and examine the file that each link points to, specify the
618 @samp{-L} option to @code{find}.  You can explicitly specify the
619 default behaviour by using the @samp{-P} option.  The @samp{-H}
620 option is a half-way-between option which ensures that any symbolic
621 links listed on the command line are dereferenced, but other symbolic
622 links are not.
624 Symbolic links are different to ``hard links'' in the sense that you
625 need permission to search the directories
626 in the linked-to file name to
627 dereference the link.  This can mean that even if you specify the
628 @samp{-L} option, @code{find} may not be able to determine the
629 properties of the file that the link points to (because you don't have
630 sufficient permission).  In this situation, @code{find} uses the
631 properties of the link itself.  This also occurs if a symbolic link
632 exists but points to a file that is missing.
634 The options controlling the behaviour of @code{find} with respect to
635 links are as follows :-
637 @table @samp
638 @item -P
639 @code{find} does not dereference symbolic links at all.  This is the
640 default behaviour.  This option must be specified before any of the
641 file names on the command line.
642 @item -H
643 @code{find} does not dereference symbolic links (except in the case of
644 file names on the command line, which are dereferenced).  If a
645 symbolic link cannot be dereferenced, the information for the symbolic
646 link itself is used.  This option must be specified before any of the
647 file names on the command line.
648 @item -L
649 @code{find} dereferences symbolic links where possible, and where this
650 is not possible it uses the properties of the symbolic link itself.
651 This option must be specified before any of the file names on the
652 command line.  Use of this option also implies the same behaviour as
653 the @samp{-noleaf} option.  If you later use the @samp{-H} or
654 @samp{-P} options, this does not turn off @samp{-noleaf}.
656 @item -follow
657 This option forms part of the ``expression'' and must be specified
658 after the file names, but it is otherwise equivalent to @samp{-L}.
659 The @samp{-follow} option affects only those tests which appear after
660 it on the command line.  This option is deprecated.  Where possible,
661 you should use @samp{-L} instead.
662 @end table
664 The following differences in behavior occur when the @samp{-L} option
665 is used:
667 @itemize @bullet
668 @item
669 @code{find} follows symbolic links to directories when searching
670 directory trees.
671 @item
672 @samp{-lname} and @samp{-ilname} always return false (unless they
673 happen to match broken symbolic links).
674 @item
675 @samp{-type} reports the types of the files that symbolic links point
676 to.  This means that in combination with @samp{-L}, @samp{-type l}
677 will be true only for broken symbolic links.  To check for symbolic
678 links when @samp{-L} has been specified, use @samp{-xtype l}.
679 @item
680 Implies @samp{-noleaf} (@pxref{Directories}).
681 @end itemize
683 If the @samp{-L} option or the @samp{-H} option is used,
684 the file names used as arguments to @samp{-newer}, @samp{-anewer}, and
685 @samp{-cnewer} are dereferenced and the timestamp from the pointed-to
686 file is used instead (if possible -- otherwise the timestamp from the
687 symbolic link is used).
689 @deffn Test -lname pattern
690 @deffnx Test -ilname pattern
691 True if the file is a symbolic link whose contents match shell pattern
692 @var{pattern}.  For @samp{-ilname}, the match is case-insensitive.
693 @xref{Shell Pattern Matching}, for details about the @var{pattern}
694 argument.  If the @samp{-L} option is in effect, this test will always
695 return false for symbolic links unless they are broken.  So, to list
696 any symbolic links to @file{sysdep.c} in the current directory and its
697 subdirectories, you can do:
699 @example
700 find . -lname '*sysdep.c'
701 @end example
702 @end deffn
704 @node Hard Links
705 @subsection Hard Links
707 Hard links allow more than one name to refer to the same file.  To
708 find all the names which refer to the same file as NAME, use
709 @samp{-samefile NAME}.  If you are not using the @samp{-L} option, you
710 can confine your search to one filesystem using the @samp{-xdev}
711 option.  This is useful because hard links cannot point outside a
712 single filesystem, so this can cut down on needless searching.
714 If the @samp{-L} option is in effect, and NAME is in fact a symbolic
715 link, the symbolic link will be dereferenced.  Hence you are searching
716 for other links (hard or symbolic) to the file pointed to by NAME.  If
717 @samp{-L} is in effect but NAME is not itself a symbolic link, other
718 symbolic links to the file NAME will be matched.
720 You can also search for files by inode number.  This can occasionally
721 be useful in diagnosing problems with filesystems for example, because
722 @code{fsck} tends to print inode numbers.  Inode numbers also
723 occasionally turn up in log messages for some types of software, and
724 are used to support the @code{ftok()} library function.
726 You can learn a file's inode number and the number of links to it by
727 running @samp{ls -li} or @samp{find -ls}.
729 You can search for hard links to inode number NUM by using @samp{-inum
730 NUM}. If there are any filesystem mount points below the directory
731 where you are starting the search, use the @samp{-xdev} option unless
732 you are also using the @samp{-L} option.  Using @samp{-xdev} this
733 saves needless searching, since hard links to a file must be on the
734 same filesystem.  @xref{Filesystems}.
736 @deffn Test -samefile NAME
737 File is a hard link to the same inode as NAME.  If the @samp{-L}
738 option is in effect, symbolic links to the same file as NAME points to
739 are also matched.
740 @end deffn
742 @deffn Test -inum n
743 File has inode number @var{n}.  The @samp{+} and @samp{-} qualifiers
744 also work, though these are rarely useful.  Much of the time it is
745 easier to use @samp{-samefile} rather than this option.
746 @end deffn
748 You can also search for files that have a certain number of links,
749 with @samp{-links}.  Directories normally have at least two hard
750 links; their @file{.} entry is the second one.  If they have
751 subdirectories, each of those also has a hard link called @file{..} to
752 its parent directory.  The @file{.} and @file{..} directory entries
753 are not normally searched unless they are mentioned on the @code{find}
754 command line.
756 @deffn Test -links n
757 File has @var{n} hard links.
758 @end deffn
760 @deffn Test -links +n
761 File has more than @var{n} hard links.
762 @end deffn
764 @deffn Test -links -n
765 File has fewer than @var{n} hard links.
766 @end deffn
768 @node Time
769 @section Time
771 Each file has three time stamps, which record the last time that
772 certain operations were performed on the file:
774 @enumerate
775 @item
776 access (read the file's contents)
777 @item
778 change the status (modify the file or its attributes)
779 @item
780 modify (change the file's contents)
781 @end enumerate
783 Some systems also provide a timestamp that indicates when a file was
784 @emph{created}.   For example, the UFS2 fileystem under NetBSD-3.1
785 records the @emph{birth time} of each file.  This information is also
786 available under other versions of BSD and some versions of Cygwin.
787 However, even on systems which support file birth time, files may
788 exist for which this information was not recorded (for example, UFS1
789 file systems simply do not contain this information).
791 You can search for files whose time stamps are within a certain age
792 range, or compare them to other time stamps.
794 @menu
795 * Age Ranges::
796 * Comparing Timestamps::
797 @end menu
799 @node Age Ranges
800 @subsection Age Ranges
802 These tests are mainly useful with ranges (@samp{+@var{n}} and
803 @samp{-@var{n}}).
805 @deffn Test -atime n
806 @deffnx Test -ctime n
807 @deffnx Test -mtime n
808 True if the file was last accessed (or its status changed, or it was
809 modified) @var{n}*24 hours ago.  The number of 24-hour periods since
810 the file's timestamp is always rounded down; therefore 0 means ``less
811 than 24 hours ago'', 1 means ``between 24 and 48 hours ago'', and so
812 forth.  Fractional values are supported but this only really makes
813 sense for the case where ranges (@samp{+@var{n}} and @samp{-@var{n}})
814 are used.
815 @end deffn
817 @deffn Test -amin n
818 @deffnx Test -cmin n
819 @deffnx Test -mmin n
820 True if the file was last accessed (or its status changed, or it was
821 modified) @var{n} minutes ago.  These tests provide finer granularity
822 of measurement than @samp{-atime} et al., but rounding is done in a
823 similar way (again, fractions are supported).  For example, to list
824 files in @file{/u/bill} that were last read from 2 to 6 minutes ago:
826 @example
827 find /u/bill -amin +2 -amin -6
828 @end example
829 @end deffn
831 @deffn Option -daystart
832 Measure times from the beginning of today rather than from 24 hours
833 ago.  So, to list the regular files in your home directory that were
834 modified yesterday, do
836 @example
837 find ~/ -daystart -type f -mtime 1
838 @end example
840 The @samp{-daystart} option is unlike most other options in that it
841 has an effect on the way that other tests are performed.  The affected
842 tests are @samp{-amin}, @samp{-cmin}, @samp{-mmin}, @samp{-atime},
843 @samp{-ctime} and @samp{-mtime}.  The @samp{-daystart} option only
844 affects the behaviour of any tests which appear after it on the
845 command line.
846 @end deffn
848 @node Comparing Timestamps
849 @subsection Comparing Timestamps
851 @deffn Test -newerXY reference
852 Succeeds if timestamp @samp{X} of the file being considered is newer
853 than timestamp @samp{Y} of the file @file{reference}.   The latters
854 @samp{X} and @samp{Y} can be any of the following letters:
856 @table @samp
857 @item a
858 Last-access time of @file{reference}
859 @item B
860 Birth time of @file{reference} (when this is not known, the test cannot succeed)
861 @item c
862 Last-change time of @file{reference}
863 @item m
864 Last-modification time of @file{reference}
865 @item t
866 The @file{reference} argument is interpreted as a literal time, rather
867 than the name of a file.  @xref{Date input formats}, for a description
868 of how the timestamp is understood.  Tests of the form @samp{-newerXt}
869 are valid but tests of the form @samp{-newertY} are not.
870 @end table
872 For example the test @code{-newerac /tmp/foo} succeeds for all files
873 which have been accessed more recently than @file{/tmp/foo} was
874 changed.   Here @samp{X} is @samp{a} and @samp{Y} is @samp{c}.   
876 Not all files have a known birth time.  If @samp{Y} is @samp{b} and
877 the birth time of @file{reference} is not available, @code{find} exits
878 with an explanatory error message.  If @samp{X} is @samp{b} and we do
879 not know the birth time the file currently being considered, the test
880 simply fails (that is, it behaves like @code{-false} does).
882 Some operating systems (for example, most implementations of Unix) do
883 not support file birth times.  Some others, for example NetBSD-3.1,
884 do.  Even on operating systems which support file birth times, the
885 information may not be available for specific files.  For example,
886 under NetBSD, file birth times are supported on UFS2 file systems, but
887 not UFS1 file systems.
889 @end deffn
893 There are two ways to list files in @file{/usr} modified after
894 February 1 of the current year.  One uses @samp{-newermt}:
896 @example
897 find /usr -newermt "Feb 1"
898 @end example
900 The other way of doing this works on the versions of find before 4.3.3:
902 @c Idea from Rick Sladkey.
903 @example
904 touch -t 02010000 /tmp/stamp$$
905 find /usr -newer /tmp/stamp$$
906 rm -f /tmp/stamp$$
907 @end example
909 @deffn Test -anewer file
910 @deffnx Test -cnewer file
911 @deffnx Test -newer file
912 True if the file was last accessed (or its status changed, or it was
913 modified) more recently than @var{file} was modified.  These tests are
914 affected by @samp{-follow} only if @samp{-follow} comes before them on
915 the command line.  @xref{Symbolic Links}, for more information on
916 @samp{-follow}.  As an example, to list any files modified since
917 @file{/bin/sh} was last modified:
919 @example
920 find . -newer /bin/sh
921 @end example
922 @end deffn
924 @deffn Test -used n
925 True if the file was last accessed @var{n} days after its status was
926 last changed.  Useful for finding files that are not being used, and
927 could perhaps be archived or removed to save disk space.
928 @end deffn
930 @node Size
931 @section Size
933 @deffn Test -size n@r{[}bckwMG@r{]}
934 True if the file uses @var{n} units of space, rounding up.  The units
935 are 512-byte blocks by default, but they can be changed by adding a
936 one-character suffix to @var{n}:
938 @table @code
939 @item b
940 512-byte blocks (never 1024)
941 @item c
942 bytes
943 @item k
944 kilobytes (1024 bytes)
945 @item w
946 2-byte words
947 @item M
948 Megabytes (units of 1048576 bytes)
949 @item G
950 Gigabytes (units of 1073741824 bytes)
951 @end table
953 The `b' suffix always considers blocks to be 512 bytes.  This is not
954 affected by the setting (or non-setting) of the POSIXLY_CORRECT
955 environment variable.  This behaviour is different to the behaviour of
956 the @samp{-ls} action).  If you want to use 1024-byte units, use the
957 `k' suffix instead.
959 The number can be prefixed with a `+' or a `-'.  A plus sign indicates
960 that the test should succeed if the file uses at least @var{n} units
961 of storage (a common use of this test) and a minus sign
962 indicates that the test should succeed if the file uses less than
963 @var{n} units of storage.  There is no `=' prefix, because that's the
964 default anyway.
966 The size does not count indirect blocks, but it does count blocks in
967 sparse files that are not actually allocated.  In other words, it's
968 consistent with the result you get for @samp{ls -l} or @samp{wc -c}.
969 This handling of sparse files differs from the output of the @samp{%k}
970 and @samp{%b} format specifiers for the @samp{-printf} predicate.
972 @end deffn
974 @deffn Test -empty
975 True if the file is empty and is either a regular file or a directory.
976 This might help determine good candidates for deletion.  This test is
977 useful with @samp{-depth} (@pxref{Directories}) and @samp{-delete}
978 (@pxref{Single File}).
979 @end deffn
981 @node Type
982 @section Type
984 @deffn Test -type c
985 True if the file is of type @var{c}:
987 @table @code
988 @item b
989 block (buffered) special
990 @item c
991 character (unbuffered) special
992 @item d
993 directory
994 @item p
995 named pipe (FIFO)
996 @item f
997 regular file
998 @item l
999 symbolic link; if @samp{-L} is in effect, this is true only for broken
1000 symbolic links.  If you want to search for symbolic links when
1001 @samp{-L} is in effect, use @samp{-xtype} instead of @samp{-type}.
1002 @item s
1003 socket
1004 @item D
1005 door (Solaris)
1006 @end table
1007 @end deffn
1009 @deffn Test -xtype c
1010 This test behaves the same as @samp{-type} unless the file is a
1011 symbolic link.  If the file is a symbolic link, the result is as
1012 follows (in the table below, @samp{X} should be understood to
1013 represent any letter except @samp{l}):
1015 @table @samp
1016 @item @samp{-P -xtype l}
1017 True if the symbolic link is broken
1018 @item @samp{-P -xtype X}
1019 True if the (ultimate) target file is of type @samp{X}.
1020 @item @samp{-L -xtype l}
1021 Always true
1022 @item @samp{-L -xtype X}
1023 False unless the symbolic link is broken
1024 @end table
1026 In other words, for symbolic links, @samp{-xtype} checks the type of
1027 the file that @samp{-type} does not check.  
1029 The @samp{-H} option also affects the behaviour of @samp{-xtype}.
1030 When @samp{-H} is in effect, @samp{-xtype} behaves as if @samp{-L} had
1031 been specified when examining files listed on the command line, and as
1032 if @samp{-P} had been specified otherwise.  If neither @samp{-H} nor
1033 @samp{-L} was specified, @samp{-xtype} behaves as if @samp{-P} had
1034 been specified.
1036 @xref{Symbolic Links}, for more information on @samp{-follow} and
1037 @samp{-L}.
1038 @end deffn
1040 @node Owner
1041 @section Owner
1043 @deffn Test -user uname
1044 @deffnx Test -group gname
1045 True if the file is owned by user @var{uname} (belongs to group
1046 @var{gname}).  A numeric ID is allowed.
1047 @end deffn
1049 @deffn Test -uid n
1050 @deffnx Test -gid n
1051 True if the file's numeric user ID (group ID) is @var{n}.  These tests
1052 support ranges (@samp{+@var{n}} and @samp{-@var{n}}), unlike
1053 @samp{-user} and @samp{-group}.
1054 @end deffn
1056 @deffn Test -nouser
1057 @deffnx Test -nogroup
1058 True if no user corresponds to the file's numeric user ID (no group
1059 corresponds to the numeric group ID).  These cases usually mean that
1060 the files belonged to users who have since been removed from the
1061 system.  You probably should change the ownership of such files to an
1062 existing user or group, using the @code{chown} or @code{chgrp}
1063 program.
1064 @end deffn
1066 @node Mode Bits
1067 @section File Mode Bits
1069 @xref{File Permissions}, for information on how file mode bits are
1070 structured and how to specify them.
1072 Four tests determine what users can do with files.  These are
1073 @samp{-readable}, @samp{-writable}, @samp{-executable} and
1074 @samp{-perm}.  The first three tests ask the operating system if the
1075 current user can perform the relevant operation on a file, while
1076 @samp{-perm} just examines the file's mode.  The file mode may give
1077 a misleading impression of what the user can actually do, because the
1078 file may have an access control list, or exist on a read-only
1079 filesystem, for example.  Of these four tests though, only
1080 @samp{-perm} is specified by the POSIX standard.
1082 The @samp{-readable}, @samp{-writable} and @samp{-executable} tests
1083 are implemented via the @code{access} system call.  This is
1084 implemented within the operating system itself.  If the file being
1085 considered is on an NFS filesystem, the remote system may allow or
1086 forbid read or write operations for reasons of which the NFS client
1087 cannot take account.  This includes user-ID mapping, either in the
1088 general sense or the more restricted sense in which remote superusers
1089 are treated by the NFS server as if they are the local user
1090 @samp{nobody} on the NFS server.
1092 None of the tests in this section should be used to verify that a user
1093 is authorised to perform any operation (on the file being tested or
1094 any other file) because of the possibility of a race condition.  That
1095 is, the situation may change between the test and an action being
1096 taken on the basis of the result of that test.
1099 @deffn Test -readable 
1100 True if the file can be read by the invoking user.
1101 @end deffn
1103 @deffn Test -writable
1104 True if the file can be written by the invoking user.  This is an
1105 in-principle check, and other things may prevent a successful write
1106 operation; for example, the filesystem might be full.
1107 @end deffn
1109 @deffn Test -executable
1110 True if the file can be executed/searched by the invoking user.
1111 @end deffn
1113 @deffn Test -perm pmode
1115 True if the file's mode bits match @var{pmode}, which can be
1116 either a symbolic or numeric @var{mode} (@pxref{File Permissions})
1117 optionally prefixed by @samp{-} or @samp{/}.
1119 A @var{pmode} that starts with neither @samp{-} nor @samp{/} matches
1120 if @var{mode} exactly matches the file mode bits.
1122 A @var{pmode} that starts with @samp{-} matches if
1123 @emph{all} the file mode bits set in @var{mode} are set for the file;
1124 bits not set in @var{mode} are ignored.
1126 A @var{pmode} that starts with @samp{/} matches if
1127 @emph{any} of the file mode bits set in @var{mode} are set for the file;
1128 bits not set in @var{mode} are ignored.
1129 This is a GNU extension.
1131 If you don't use the @samp{/} or @samp{-} form with a symbolic mode
1132 string, you may have to specify a rather complex mode string.  For
1133 example @samp{-perm g=w} will only match files that have mode 0020
1134 (that is, ones for which group write permission is the only file mode bit
1135 set).  It is more likely that you will want to use the @samp{/} or
1136 @samp{-} forms, for example @samp{-perm -g=w}, which matches any file
1137 with group write permission.
1140 @table @samp
1141 @item -perm 664
1142 Match files that have read and write permission for their owner,
1143 and group, but that the rest of the world can read but not write to.
1144 Do not match files that meet these criteria but have other file mode
1145 bits set (for example if someone can execute/search the file).
1147 @item -perm -664
1148 Match files that have read and write permission for their owner,
1149 and group, but that the rest of the world can read but not write to,
1150 without regard to the presence of any extra file mode bits (for
1151 example the executable bit).  This matches a file with mode
1152 0777, for example.
1154 @item -perm /222
1155 Match files that are writable by somebody (their owner, or
1156 their group, or anybody else).
1158 @item -perm /022
1159 Match files that are writable by either their owner or their
1160 group.  The files don't have to be writable by both the owner and
1161 group to be matched; either will do.
1163 @item -perm /g+w,o+w
1164 As above.
1166 @item -perm /g=w,o=w
1167 As above.
1169 @item -perm -022
1170 Match files that are writable by both their owner and their
1171 group.
1173 @item -perm -444 -perm /222 ! -perm /111
1174 Match files that are readable for everybody, have at least one
1175 write bit set (i.e., somebody can write to them), but that cannot be
1176 executed/searched by anybody.  Note that in some shells the @samp{!} must be
1177 escaped;.
1179 @item -perm -a+r -perm /a+w ! -perm /a+x
1180 As above.
1183 @item -perm -g+w,o+w
1184 As above.
1185 @end table
1187 @quotation Warning
1188 If you specify @samp{-perm /000} or @samp{-perm /mode} where the
1189 symbolic mode @samp{mode} has no bits set, the test currently matches
1190 no files.  This differs from the behaviour of @samp{-perm -000}, which
1191 matches all files.  The behaviour of @samp{-perm /000} will be changed
1192 to be consistent with the behaviour of @samp{-perm -000}.  The change
1193 will probably be made in early 2006.
1194 @end quotation
1196 @end deffn
1198 @node Contents
1199 @section Contents
1201 To search for files based on their contents, you can use the
1202 @code{grep} program.  For example, to find out which C source files in
1203 the current directory contain the string @samp{thing}, you can do:
1205 @example
1206 grep -l thing *.[ch]
1207 @end example
1209 If you also want to search for the string in files in subdirectories,
1210 you can combine @code{grep} with @code{find} and @code{xargs}, like
1211 this:
1213 @example
1214 find . -name '*.[ch]' | xargs grep -l thing
1215 @end example
1217 The @samp{-l} option causes @code{grep} to print only the names of
1218 files that contain the string, rather than the lines that contain it.
1219 The string argument (@samp{thing}) is actually a regular expression,
1220 so it can contain metacharacters.  This method can be refined a little
1221 by using the @samp{-r} option to make @code{xargs} not run @code{grep}
1222 if @code{find} produces no output, and using the @code{find} action
1223 @samp{-print0} and the @code{xargs} option @samp{-0} to avoid
1224 misinterpreting files whose names contain spaces:
1226 @example
1227 find . -name '*.[ch]' -print0 | xargs -r -0 grep -l thing
1228 @end example
1230 For a fuller treatment of finding files whose contents match a
1231 pattern, see the manual page for @code{grep}.
1233 @node Directories
1234 @section Directories
1236 Here is how to control which directories @code{find} searches, and how
1237 it searches them.  These two options allow you to process a horizontal
1238 slice of a directory tree.
1240 @deffn Option -maxdepth levels
1241 Descend at most @var{levels} (a non-negative integer) levels of
1242 directories below the command line arguments.  @samp{-maxdepth 0}
1243 means only apply the tests and actions to the command line arguments.
1244 @end deffn
1246 @deffn Option -mindepth levels
1247 Do not apply any tests or actions at levels less than @var{levels} (a
1248 non-negative integer).  @samp{-mindepth 1} means process all files
1249 except the command line arguments.
1250 @end deffn
1252 @deffn Option -depth
1253 Process each directory's contents before the directory itself.  Doing
1254 this is a good idea when producing lists of files to archive with
1255 @code{cpio} or @code{tar}.  If a directory does not have write
1256 permission for its owner, its contents can still be restored from the
1257 archive since the directory's permissions are restored after its
1258 contents.
1259 @end deffn
1261 @deffn Option -d
1262 This is a deprecated synonym for @samp{-depth}, for compatibility with
1263 Mac OS X, FreeBSD and OpenBSD.  The @samp{-depth} option is a POSIX
1264 feature, so it is better to use that.
1265 @end deffn
1267 @deffn Action -prune
1268 If the file is a directory, do not descend into it.  The result is
1269 true.  For example, to skip the directory @file{src/emacs} and all
1270 files and directories under it, and print the names of the other files
1271 found:
1273 @example
1274 find . -wholename './src/emacs' -prune -o -print
1275 @end example
1277 The above command will not print @file{./src/emacs} among its list of
1278 results.  This however is not due to the effect of the @samp{-prune}
1279 action (which only prevents further descent, it doesn't make sure we
1280 ignore that item).  Instead, this effect is due to the use of
1281 @samp{-o}.  Since the left hand side of the ``or'' condition has
1282 succeeded for @file{./src/emacs}, it is not necessary to evaluate the
1283 right-hand-side (@samp{-print}) at all for this particular file.  If
1284 you wanted to print that directory name you could use either an extra
1285 @samp{-print} action:
1287 @example
1288 find . -wholename './src/emacs' -prune -print -o -print
1289 @end example
1291 or use the comma operator:
1293 @example
1294 find . -wholename './src/emacs' -prune , -print
1295 @end example
1297 If the @samp{-depth} option is in effect, the subdirectories will have
1298 already been visited in any case.  Hence @samp{-prune} has no effect
1299 and returns false.
1300 @end deffn
1303 @deffn Action -quit
1304 Exit immediately (with return value zero if no errors have occurred).
1305 No child processes will be left running, but no more files specified
1306 on the command line will be processed.  For example, @code{find
1307 /tmp/foo /tmp/bar -print -quit} will print only @samp{/tmp/foo}.  Any
1308 command lines which have been built by @samp{-exec ... \+} or
1309 @samp{-execdir ... \+} are invoked before the program is executed.
1310 @end deffn
1312 @deffn Option -noleaf
1313 Do not optimize by assuming that directories contain 2 fewer
1314 subdirectories than their hard link count.  This option is needed when
1315 searching filesystems that do not follow the Unix directory-link
1316 convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount
1317 points.  Each directory on a normal Unix filesystem has at least 2
1318 hard links: its name and its @file{.}  entry.  Additionally, its
1319 subdirectories (if any) each have a @file{..}  entry linked to that
1320 directory.  When @code{find} is examining a directory, after it has
1321 statted 2 fewer subdirectories than the directory's link count, it
1322 knows that the rest of the entries in the directory are
1323 non-directories (@dfn{leaf} files in the directory tree).  If only the
1324 files' names need to be examined, there is no need to stat them; this
1325 gives a significant increase in search speed.
1326 @end deffn
1328 @deffn Option -ignore_readdir_race
1329 If a file disappears after its name has been read from a directory but
1330 before @code{find} gets around to examining the file with @code{stat},
1331 don't issue an error message.  If you don't specify this option, an
1332 error message will be issued.  This option can be useful in system
1333 scripts (cron scripts, for example) that examine areas of the
1334 filesystem that change frequently (mail queues, temporary directories,
1335 and so forth), because this scenario is common for those sorts of
1336 directories.  Completely silencing error messages from @code{find} is
1337 undesirable, so this option neatly solves the problem.  There is no
1338 way to search one part of the filesystem with this option on and part
1339 of it with this option off, though.  When this option is turned on and 
1340 find discovers that one of the start-point files specified on the
1341 command line does not exist, no error message will be issued.
1343 @end deffn
1345 @deffn Option -noignore_readdir_race
1346 This option reverses the effect of the @samp{-ignore_readdir_race}
1347 option.
1348 @end deffn
1351 @node Filesystems
1352 @section Filesystems
1354 A @dfn{filesystem} is a section of a disk, either on the local host or
1355 mounted from a remote host over a network.  Searching network
1356 filesystems can be slow, so it is common to make @code{find} avoid
1357 them.
1359 There are two ways to avoid searching certain filesystems.  One way is
1360 to tell @code{find} to only search one filesystem:
1362 @deffn Option -xdev
1363 @deffnx Option -mount
1364 Don't descend directories on other filesystems.  These options are
1365 synonyms.
1366 @end deffn
1368 The other way is to check the type of filesystem each file is on, and
1369 not descend directories that are on undesirable filesystem types:
1371 @deffn Test -fstype type
1372 True if the file is on a filesystem of type @var{type}.  The valid
1373 filesystem types vary among different versions of Unix; an incomplete
1374 list of filesystem types that are accepted on some version of Unix or
1375 another is:
1376 @example
1377 ext2 ext3 proc sysfs ufs 4.2 4.3 nfs tmp mfs S51K S52K
1378 @end example
1379 You can use @samp{-printf} with the @samp{%F} directive to see the
1380 types of your filesystems.  The @samp{%D} directive shows the device
1381 number.  @xref{Print File Information}.  @samp{-fstype} is usually
1382 used with @samp{-prune} to avoid searching remote filesystems
1383 (@pxref{Directories}).
1384 @end deffn
1386 @node Combining Primaries With Operators
1387 @section Combining Primaries With Operators
1389 Operators build a complex expression from tests and actions.
1390 The operators are, in order of decreasing precedence:
1392 @table @code
1393 @item @asis{( @var{expr} )}
1394 @findex ()
1395 Force precedence.  True if @var{expr} is true.
1397 @item @asis{! @var{expr}}
1398 @itemx @asis{-not @var{expr}}
1399 @findex !
1400 @findex -not
1401 True if @var{expr} is false.  In some shells, it is necessary to
1402 protect the @samp{!} from shell interpretation by quoting it.
1404 @item @asis{@var{expr1 expr2}}
1405 @itemx @asis{@var{expr1} -a @var{expr2}}
1406 @itemx @asis{@var{expr1} -and @var{expr2}}
1407 @findex -a
1408 @findex -and
1409 And; @var{expr2} is not evaluated if @var{expr1} is false.
1411 @item @asis{@var{expr1} -o @var{expr2}}
1412 @itemx @asis{@var{expr1} -or @var{expr2}}
1413 @findex -o
1414 @findex -or
1415 Or; @var{expr2} is not evaluated if @var{expr1} is true.
1417 @item @asis{@var{expr1} , @var{expr2}}
1418 @findex ,
1419 List; both @var{expr1} and @var{expr2} are always evaluated.  True if
1420 @var{expr2} is true.  The value of @var{expr1} is discarded.  This
1421 operator lets you do multiple independent operations on one traversal,
1422 without depending on whether other operations succeeded.  The two
1423 operations @var{expr1} and @var{expr2} are not always fully
1424 independent, since @var{expr1} might have side effects like touching
1425 or deleting files, or it might use @samp{-prune} which would also
1426 affect @var{expr2}.
1427 @end table
1429 @code{find} searches the directory tree rooted at each file name by
1430 evaluating the expression from left to right, according to the rules
1431 of precedence, until the outcome is known (the left hand side is false
1432 for @samp{-and}, true for @samp{-or}), at which point @code{find}
1433 moves on to the next file name.
1435 There are two other tests that can be useful in complex expressions:
1437 @deffn Test -true
1438 Always true.
1439 @end deffn
1441 @deffn Test -false
1442 Always false.
1443 @end deffn
1445 @node Actions
1446 @chapter Actions
1448 There are several ways you can print information about the files that
1449 match the criteria you gave in the @code{find} expression.  You can
1450 print the information either to the standard output or to a file that
1451 you name.  You can also execute commands that have the file names as
1452 arguments.  You can use those commands as further filters to select
1453 files.
1455 @menu
1456 * Print File Name::
1457 * Print File Information::
1458 * Run Commands::
1459 * Delete Files::
1460 * Adding Tests::
1461 @end menu
1463 @node Print File Name
1464 @section Print File Name
1466 @deffn Action -print
1467 True; print the entire file name on the standard output, followed by a
1468 newline.  If there is the faintest possibility that one of the files
1469 for which you are searching might contain a newline, you should use
1470 @samp{-print0} instead.
1471 @end deffn
1473 @deffn Action -fprint file
1474 True; print the entire file name into file @var{file}, followed by a
1475 newline.  If @var{file} does not exist when @code{find} is run, it is
1476 created; if it does exist, it is truncated to 0 bytes.  The named
1477 output file is always created, even if no output is sent to it.  The
1478 file names @file{/dev/stdout} and @file{/dev/stderr} are handled
1479 specially; they refer to the standard output and standard error
1480 output, respectively.
1482 If there is the faintest possibility that one of the files for which
1483 you are searching might contain a newline, you should use
1484 @samp{-fprint0} instead.
1485 @end deffn
1488 @c @deffn Option -show-control-chars how
1489 @c This option affects how some of @code{find}'s actions treat
1490 @c unprintable characters in file names.  If @samp{how} is
1491 @c @samp{literal}, any subsequent actions (i.e., actions further on in the
1492 @c command line) print file names as-is.  
1493 @c 
1494 @c If this option is not specified, it currently defaults to @samp{safe}.
1495 @c If @samp{how} is @samp{safe}, C-like backslash escapes are used to
1496 @c indicate the non-printable characters for @samp{-ls} and @samp{-fls}.
1497 @c On the other hand, @samp{-print}, @samp{-fprint}, @samp{-fprintf} and
1498 @c @code{-printf} all quote unprintable characters if the data is going
1499 @c to a tty, and otherwise the data is emitted literally.
1500 @c 
1501 @c @table @code
1502 @c @item -ls
1503 @c Escaped if @samp{how} is @samp{safe}
1504 @c @item -fls
1505 @c Escaped if @samp{how} is @samp{safe}
1506 @c @item -print
1507 @c Always quoted if stdout is a tty,
1508 @c @samp{-show-control-chars} is ignored
1509 @c @item -print0
1510 @c Always literal, never escaped
1511 @c @item -fprint
1512 @c Always quoted if the destination is a tty;
1513 @c @samp{-show-control-chars} is ignored
1514 @c @item -fprint0
1515 @c Always literal, never escaped
1516 @c @item -fprintf
1517 @c If the destination is a tty, the @samp{%f}, 
1518 @c @samp{%F}, @samp{%h}, @samp{%l}, @samp{%p},
1519 @c and @samp{%P} directives produce quoted
1520 @c strings if stdout is a tty and are treated
1521 @c literally otherwise.
1522 @c @item -printf
1523 @c As for @code{-fprintf}.
1524 @c @end table
1525 @c @end deffn
1528 @node Print File Information
1529 @section Print File Information
1531 @deffn Action -ls
1532 True; list the current file in @samp{ls -dils} format on the standard
1533 output.  The output looks like this:
1535 @smallexample
1536 204744   17 -rw-r--r--   1 djm      staff       17337 Nov  2  1992 ./lwall-quotes
1537 @end smallexample
1539 The fields are:
1541 @enumerate
1542 @item
1543 The inode number of the file.  @xref{Hard Links}, for how to find
1544 files based on their inode number.
1546 @item
1547 the number of blocks in the file.  The block counts are of 1K blocks,
1548 unless the environment variable @code{POSIXLY_CORRECT} is set, in
1549 which case 512-byte blocks are used.  @xref{Size}, for how to find
1550 files based on their size.
1552 @item
1553 The file's type and file mode bits.  The type is shown as a dash for a
1554 regular file; for other file types, a letter like for @samp{-type} is
1555 used (@pxref{Type}).  The file mode bits are read, write, and execute/search for
1556 the file's owner, its group, and other users, respectively; a dash
1557 means the permission is not granted.  @xref{File Permissions}, for
1558 more details about file permissions.  @xref{Mode Bits}, for how to
1559 find files based on their file mode bits.
1561 @item
1562 The number of hard links to the file.
1564 @item
1565 The user who owns the file.
1567 @item
1568 The file's group.
1570 @item
1571 The file's size in bytes.
1573 @item
1574 The date the file was last modified.
1576 @item
1577 The file's name.  @samp{-ls} quotes non-printable characters in the
1578 file names using C-like backslash escapes.  This may change soon, as
1579 the treatment of unprintable characters is harmonised for @samp{-ls},
1580 @samp{-fls}, @samp{-print}, @samp{-fprint}, @samp{-printf} and
1581 @samp{-fprintf}.
1582 @end enumerate
1583 @end deffn
1585 @deffn Action -fls file
1586 True; like @samp{-ls} but write to @var{file} like @samp{-fprint}
1587 (@pxref{Print File Name}).  The named output file is always created,
1588 even if no output is sent to it.
1589 @end deffn
1591 @deffn Action -printf format
1592 True; print @var{format} on the standard output, interpreting @samp{\}
1593 escapes and @samp{%} directives.  Field widths and precisions can be
1594 specified as with the @code{printf} C function.  Format flags (like
1595 @samp{#} for example) may not work as you expect because many of the
1596 fields, even numeric ones, are printed with %s.  Numeric flags which
1597 are affected in this way include G, U, b, D, k and n.  This difference
1598 in behaviour means though that the format flag @samp{-} will work; it
1599 forces left-alignment of the field.  Unlike @samp{-print},
1600 @samp{-printf} does not add a newline at the end of the string.  If
1601 you want a newline at the end of the string, add a @samp{\n}.
1602 @end deffn
1604 @deffn Action -fprintf file format
1605 True; like @samp{-printf} but write to @var{file} like @samp{-fprint}
1606 (@pxref{Print File Name}).  The output file is always created, even if
1607 no output is ever sent to it.
1608 @end deffn
1610 @menu
1611 * Escapes::
1612 * Format Directives::
1613 * Time Formats::
1614 @end menu
1616 @node Escapes
1617 @subsection Escapes
1619 The escapes that @samp{-printf} and @samp{-fprintf} recognise are:
1621 @table @code
1622 @item \a
1623 Alarm bell.
1624 @item \b
1625 Backspace.
1626 @item \c
1627 Stop printing from this format immediately and flush the output.
1628 @item \f
1629 Form feed.
1630 @item \n
1631 Newline.
1632 @item \r
1633 Carriage return.
1634 @item \t
1635 Horizontal tab.
1636 @item \v
1637 Vertical tab.
1638 @item \\
1639 A literal backslash (@samp{\}).
1640 @item \0
1641 ASCII NUL.
1642 @item \NNN
1643 The character whose ASCII code is NNN (octal).
1644 @end table
1646 A @samp{\} character followed by any other character is treated as an
1647 ordinary character, so they both are printed, and a warning message is
1648 printed to the standard error output (because it was probably a typo).
1650 @node Format Directives
1651 @subsection Format Directives
1653 @samp{-printf} and @samp{-fprintf} support the following format
1654 directives to print information about the file being processed.  The C
1655 @code{printf} function, field width and precision specifiers are
1656 supported, as applied to string (%s) types. That is, you can specify
1657 "minimum field width"."maximum field width" for each directive.
1658 Format flags (like @samp{#} for example) may not work as you expect
1659 because many of the fields, even numeric ones, are printed with %s.
1660 The format flag @samp{-} does work; it forces left-alignment of the
1661 field.
1663 @samp{%%} is a literal percent sign.  A @samp{%} character followed by
1664 an unrecognised character (i.e., not a known directive or @code{printf}
1665 field width and precision specifier), is discarded (but the
1666 unrecognised character is printed), and a warning message is printed
1667 to the standard error output (because it was probably a typo).  Don't
1668 rely on this behaviour, because other directives may be added in the
1669 future.
1671 A @samp{%} at the end of the format argument causes undefined
1672 behaviour since there is no following character.  In some locales, it
1673 may hide your door keys, while in others it may remove the final page
1674 from the novel you are reading.
1676 @menu
1677 * Name Directives::
1678 * Ownership Directives::
1679 * Size Directives::
1680 * Location Directives::
1681 * Time Directives::
1682 * Formatting Flags::
1683 @end menu
1685 @node Name Directives
1686 @subsubsection Name Directives
1688 @table @code
1689 @item %p
1690 @c supports %-X.Yp
1691 File's name (not the absolute path name, but the name of the file as
1692 it was encountered by @code{find} - that is, as a relative path from
1693 one of the starting points).
1694 @item %f
1695 File's name with any leading directories removed (only the last
1696 element).
1697 @c supports %-X.Yf
1698 @item %h
1699 Leading directories of file's name (all but the last element and the
1700 slash before it).  If the file's name contains no slashes (for example
1701 because it was named on the command line and is in the current working
1702 directory), then ``%h'' expands to ``.''.  This prevents ``%h/%f''
1703 expanding to ``/foo'', which would be surprising and probably not
1704 desirable.
1705 @c supports %-X.Yh
1706 @item %P
1707 File's name with the name of the command line argument under which
1708 it was found removed from the beginning.
1709 @c supports %-X.YP
1710 @item %H
1711 Command line argument under which file was found.
1712 @c supports %-X.YH
1713 @end table
1715 @node Ownership Directives
1716 @subsubsection Ownership Directives
1718 @table @code
1719 @item %g
1720 @c supports %-X.Yg
1721 File's group name, or numeric group ID if the group has no name.
1722 @item %G
1723 @c supports %-X.Yg
1724 @c TODO: Needs to support # flag and 0 flag
1725 File's numeric group ID.
1726 @item %u
1727 @c supports %-X.Yu
1728 File's user name, or numeric user ID if the user has no name.
1729 @item %U
1730 @c supports %-X.Yu
1731 @c TODO: Needs to support # flag
1732 File's numeric user ID.
1733 @item %m
1734 @c full support, including # and 0.
1735 File's mode bits (in octal).  If you always want to have a leading
1736 zero on the number, use the '#' format flag, for example '%#m'.  
1738 The file mode bit numbers used are the traditional Unix
1739 numbers, which will be as expected on most systems, but if your
1740 system's file mode bit layout differs from the traditional Unix
1741 semantics, you will see a difference between the mode as printed by
1742 @samp{%m} and the mode as it appears in @code{struct stat}.
1744 @item %M
1745 File's type and mode bits (in symbolic form, as for @code{ls}).  This
1746 directive is supported in findutils 4.2.5 and later.
1747 @end table
1749 @node Size Directives
1750 @subsubsection Size Directives
1752 @table @code
1753 @item %k
1754 The amount of disk space used for this file in 1K blocks. Since disk
1755 space is allocated in multiples of the filesystem block size this is
1756 usually greater than %s/1024, but it can also be smaller if the file
1757 is a sparse file (that is, it has ``holes'').
1758 @item %b
1759 The amount of disk space used for this file in 512-byte blocks. Since
1760 disk space is allocated in multiples of the filesystem block size this
1761 is usually greater than %s/1024, but it can also be smaller if the
1762 file is a sparse file (that is, it has ``holes'').
1763 @item %s
1764 File's size in bytes.
1765 @end table
1767 @node Location Directives
1768 @subsubsection Location Directives
1770 @table @code
1771 @item %d
1772 File's depth in the directory tree (depth below a file named on the
1773 command line, not depth below the root directory).  Files named on the
1774 command line have a depth of 0.  Subdirectories immediately below them
1775 have a depth of 1, and so on.
1776 @item %D
1777 The device number on which the file exists (the @code{st_dev} field of
1778 @code{struct stat}), in decimal.
1779 @item %F
1780 Type of the filesystem the file is on; this value can be used for
1781 @samp{-fstype} (@pxref{Directories}).
1782 @item %l
1783 Object of symbolic link (empty string if file is not a symbolic link).
1784 @item %i
1785 File's inode number (in decimal).
1786 @item %n
1787 Number of hard links to file.
1788 @item %y
1789 Type of the file as used with @samp{-type}.  If the file is a symbolic
1790 link, @samp{l} will be printed.
1791 @item %Y
1792 Type of the file as used with @samp{-type}.  If the file is a symbolic
1793 link, it is dereferenced.  If the file is a broken symbolic link,
1794 @samp{N} is printed.
1796 @end table
1798 @node Time Directives
1799 @subsubsection Time Directives
1801 Some of these directives use the C @code{ctime} function.  Its output
1802 depends on the current locale, but it typically looks like
1804 @example
1805 Wed Nov  2 00:42:36 1994
1806 @end example
1808 @table @code
1809 @item %a
1810 File's last access time in the format returned by the C @code{ctime}
1811 function.
1812 @item %A@var{k}
1813 File's last access time in the format specified by @var{k}
1814 (@pxref{Time Formats}).
1815 @item %c
1816 File's last status change time in the format returned by the C
1817 @code{ctime} function.
1818 @item %C@var{k}
1819 File's last status change time in the format specified by @var{k}
1820 (@pxref{Time Formats}).
1821 @item %t
1822 File's last modification time in the format returned by the C
1823 @code{ctime} function.
1824 @item %T@var{k}
1825 File's last modification time in the format specified by @var{k}
1826 (@pxref{Time Formats}).
1827 @end table
1829 @node Time Formats
1830 @subsection Time Formats
1832 Below are the formats for the directives @samp{%A}, @samp{%C}, and
1833 @samp{%T}, which print the file's timestamps.  Some of these formats
1834 might not be available on all systems, due to differences in the C
1835 @code{strftime} function between systems.
1837 @menu
1838 * Time Components::
1839 * Date Components::
1840 * Combined Time Formats::
1841 @end menu
1843 @node Time Components
1844 @subsubsection Time Components
1846 The following format directives print single components of the time.
1848 @table @code
1849 @item H
1850 hour (00..23)
1851 @item I
1852 hour (01..12)
1853 @item k
1854 hour ( 0..23)
1855 @item l
1856 hour ( 1..12)
1857 @item p
1858 locale's AM or PM
1859 @item Z
1860 time zone (e.g., EDT), or nothing if no time zone is determinable
1861 @item M
1862 minute (00..59)
1863 @item S
1864 second (00..61)
1865 @item @@
1866 seconds since Jan. 1, 1970, 00:00 GMT.
1867 @end table
1869 @node Date Components
1870 @subsubsection Date Components
1872 The following format directives print single components of the date.
1874 @table @code
1875 @item a
1876 locale's abbreviated weekday name (Sun..Sat)
1877 @item A
1878 locale's full weekday name, variable length (Sunday..Saturday)
1879 @item b
1880 @itemx h
1881 locale's abbreviated month name (Jan..Dec)
1882 @item B
1883 locale's full month name, variable length (January..December)
1884 @item m
1885 month (01..12)
1886 @item d
1887 day of month (01..31)
1888 @item w
1889 day of week (0..6)
1890 @item j
1891 day of year (001..366)
1892 @item U
1893 week number of year with Sunday as first day of week (00..53)
1894 @item W
1895 week number of year with Monday as first day of week (00..53)
1896 @item Y
1897 year (1970@dots{})
1898 @item y
1899 last two digits of year (00..99)
1900 @end table
1902 @node Combined Time Formats
1903 @subsubsection Combined Time Formats
1905 The following format directives print combinations of time and date
1906 components.
1908 @table @code
1909 @item r
1910 time, 12-hour (hh:mm:ss [AP]M)
1911 @item T
1912 time, 24-hour (hh:mm:ss)
1913 @item X
1914 locale's time representation (H:M:S)
1915 @item c
1916 locale's date and time (Sat Nov 04 12:02:33 EST 1989)
1917 @item D
1918 date (mm/dd/yy)
1919 @item x
1920 locale's date representation (mm/dd/yy)
1921 @item +
1922 Date and time, separated by '+', for example `2004-04-28+22:22:05'.
1923 The time is given in the current timezone (which may be affected by
1924 setting the TZ environment variable).  This is a GNU extension.
1925 @end table
1927 @node Formatting Flags
1928 @subsubsection Formatting Flags
1930 The @samp{%m} and @samp{%d} directives support the @samp{#}, @samp{0}
1931 and @samp{+} flags, but the other directives do not, even if they
1932 print numbers.  Numeric directives that do not support these flags
1933 include
1935 @samp{G},
1936 @samp{U},
1937 @samp{b},
1938 @samp{D},
1939 @samp{k} and
1940 @samp{n}.
1942 All fields support the format flag @samp{-}, which makes fields
1943 left-aligned.  That is, if the field width is greater than the actual
1944 contents of the field, the requisite number of spaces are printed
1945 after the field content instead of before it.
1947 @node Run Commands
1948 @section Run Commands
1950 You can use the list of file names created by @code{find} or
1951 @code{locate} as arguments to other commands.  In this way you can
1952 perform arbitrary actions on the files.
1954 @menu
1955 * Single File::
1956 * Multiple Files::
1957 * Querying::
1958 @end menu
1960 @node Single File
1961 @subsection Single File
1963 Here is how to run a command on one file at a time.
1965 @deffn Action -execdir command ;
1966 Execute @var{command}; true if zero status is returned.  @code{find}
1967 takes all arguments after @samp{-exec} to be part of the command until
1968 an argument consisting of @samp{;} is reached.  It replaces the string
1969 @samp{@{@}} by the current file name being processed everywhere it
1970 occurs in the command.  Both of these constructions need to be escaped
1971 (with a @samp{\}) or quoted to protect them from expansion by the
1972 shell.  The command is executed in the directory in which @code{find}
1973 was run.
1975 For example, to compare each C header file in or below the current
1976 directory with the file @file{/tmp/master}:
1978 @example
1979 find . -name '*.h' -execdir diff -u '@{@}' /tmp/master ';'
1980 @end example
1981 @end deffn
1983 If you use @samp{-execdir}, you must ensure that the current directory
1984 is not on @var{$PATH}, because otherwise an attacker could make
1985 @samp{find} run commands of their choice simply by leaving a
1986 suitably-named file in the right directory.  GNU find will refuse to
1987 run if you use @samp{-execdir} and the current directory is in
1988 @var{$PATH}.
1990 Another similar option, @samp{-exec} is supported, but is less secure.
1991 @xref{Security Considerations}, for a discussion of the security
1992 problems surrounding @samp{-exec}.
1995 @deffn Action -exec command ;
1996 This insecure variant of the @samp{-execdir} action is specified by
1997 POSIX.  The main difference is that the command is executed in the
1998 directory from which @code{find} was invoked, meaning that @samp{@{@}}
1999 is expanded to a relative path starting with the name of one of the
2000 starting directories, rather than just the basename of the matched
2001 file.
2003 While some implementations of @code{find} replace the @samp{@{@}} only
2004 where it appears on its own in an argument, GNU @code{find} replaces
2005 @samp{@{@}} wherever it appears.
2006 @end deffn
2009 @node Multiple Files
2010 @subsection Multiple Files
2012 Sometimes you need to process files one at a time.  But usually this
2013 is not necessary, and, it is faster to run a command on as many files
2014 as possible at a time, rather than once per file.  Doing this saves on
2015 the time it takes to start up the command each time.
2017 The @samp{-execdir} and @samp{-exec} actions have variants that build
2018 command lines containing as many matched files as possible.
2020 @deffn Action -execdir command @{@} +
2021 This works as for @samp{-execdir command ;}, except that the
2022 @samp{@{@}} at the end of the command is expanded to a list of names
2023 of matching files.  This expansion is done in such a way as to avoid
2024 exceeding the maximum command line length available on the system.
2025 Only one @samp{@{@}} is allowed within the command, and it must appear
2026 at the end, immediately before the @samp{+}.  A @samp{+} appearing in
2027 any position other than immediately after @samp{@{@}} is not
2028 considered to be special (that is, it does not terminate the command).
2029 @end deffn
2032 @deffn Action -exec command @{@} +
2033 This insecure variant of the @samp{-execdir} action is specified by
2034 POSIX.  The main difference is that the command is executed in the
2035 directory from which @code{find} was invoked, meaning that @samp{@{@}}
2036 is expanded to a relative path starting with the name of one of the
2037 starting directories, rather than just the basename of the matched
2038 file.
2039 @end deffn
2041 Before @code{find} exits, any partially-built command lines are
2042 executed.  This happens even if the exit was caused by the
2043 @samp{-quit} action.  However, some types of error (for example not
2044 being able to invoke @code{stat()} on the current directory) can cause
2045 an immediate fatal exit.  In this situation, any partially-built
2046 command lines will not be invoked (this prevents possible infinite
2047 loops).
2049 At first sight, it looks like the list of filenames to be processed
2050 can only be at the end of the command line, and that this might be a
2051 problem for some comamnds (@code{cp} and @code{rsync} for example).
2053 However, there is a slightly obscure but powerful workarouund for this
2054 problem which takes advantage of the behaviour of @code{sh -c}:-
2056 @example
2057 find startpoint -tests @dots{} -exec sh -c 'scp "$@@" remote:/dest' sh @{@} + 
2058 @end example
2060 In the example above, the filenames we want to work on need to occur
2061 on the @code{scp} command line before the name of the destination.  We
2062 use the shell to invoke the command @code{scp "$@@" remote:/dest} and
2063 the shell expands @code{"$@@"} to the list of filenames we want to
2064 process.
2066 Another, but less secure, way to run a command on more than one file
2067 at once, is to use the @code{xargs} command, which is invoked like
2068 this:
2070 @example
2071 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
2072 @end example
2074 @code{xargs} normally reads arguments from the standard input.  These
2075 arguments are delimited by blanks (which can be protected with double
2076 or single quotes or a backslash) or newlines.  It executes the
2077 @var{command} (default is @file{/bin/echo}) one or more times with any
2078 @var{initial-arguments} followed by arguments read from standard
2079 input.  Blank lines on the standard input are ignored.  If the
2080 @samp{-L} option is in use, trailing blanks indicate that @code{xargs}
2081 should consider the following line to be part of this one.
2083 Instead of blank-delimited names, it is safer to use @samp{find
2084 -print0} or @samp{find -fprint0} and process the output by giving the
2085 @samp{-0} or @samp{--null} option to GNU @code{xargs}, GNU @code{tar},
2086 GNU @code{cpio}, or @code{perl}.  The @code{locate} command also has a
2087 @samp{-0} or @samp{--null} option which does the same thing.
2089 You can use shell command substitution (backquotes) to process a list
2090 of arguments, like this:
2092 @example
2093 grep -l sprintf `find $HOME -name '*.c' -print`
2094 @end example
2096 However, that method produces an error if the length of the @samp{.c}
2097 file names exceeds the operating system's command line length limit.
2098 @code{xargs} avoids that problem by running the command as many times
2099 as necessary without exceeding the limit:
2101 @example
2102 find $HOME -name '*.c' -print | xargs grep -l sprintf
2103 @end example
2105 However, if the command needs to have its standard input be a terminal
2106 (@code{less}, for example), you have to use the shell command
2107 substitution method or use the @samp{--arg-file} option of
2108 @code{xargs}.
2110 The @code{xargs} command will process all its input, building command
2111 lines and executing them, unless one of the commands exits with a
2112 status of 255 (this will cause xargs to issue an error message and
2113 stop) or it reads a line contains the end of file string specified
2114 with the @samp{--eof} option.
2116 @menu
2117 * Unsafe File Name Handling::
2118 * Safe File Name Handling::
2119 * Unusual Characters in File Names::
2120 * Limiting Command Size::
2121 * Interspersing File Names::
2122 @end menu
2124 @node Unsafe File Name Handling
2125 @subsubsection Unsafe File Name Handling
2127 Because file names can contain quotes, backslashes, blank characters,
2128 and even newlines, it is not safe to process them using @code{xargs}
2129 in its default mode of operation.  But since most files' names do not
2130 contain blanks, this problem occurs only infrequently.  If you are
2131 only searching through files that you know have safe names, then you
2132 need not be concerned about it.
2134 @c This example is adapted from:
2135 @c From: pfalstad@stone.Princeton.EDU (Paul John Falstad)
2136 @c Newsgroups: comp.unix.shell
2137 @c Subject: Re: Beware xargs security holes
2138 @c Date: 16 Oct 90 19:12:06 GMT
2140 In many applications, if @code{xargs} botches processing a file
2141 because its name contains special characters, some data might be lost.
2142 The importance of this problem depends on the importance of the data
2143 and whether anyone notices the loss soon enough to correct it.
2144 However, here is an extreme example of the problems that using
2145 blank-delimited names can cause.  If the following command is run
2146 daily from @code{cron}, then any user can remove any file on the
2147 system:
2149 @example
2150 find / -name '#*' -atime +7 -print | xargs rm
2151 @end example
2153 For example, you could do something like this:
2155 @example
2156 eg$ echo > '#
2157 vmunix'
2158 @end example
2160 @noindent
2161 and then @code{cron} would delete @file{/vmunix}, if it ran
2162 @code{xargs} with @file{/} as its current directory.
2164 To delete other files, for example @file{/u/joeuser/.plan}, you could
2165 do this:
2167 @example
2168 eg$ mkdir '#
2170 eg$ cd '#
2172 eg$ mkdir u u/joeuser u/joeuser/.plan'
2174 eg$ echo > u/joeuser/.plan'
2175 /#foo'
2176 eg$ cd ..
2177 eg$ find . -name '#*' -print | xargs echo
2178 ./# ./# /u/joeuser/.plan /#foo
2179 @end example
2181 @node Safe File Name Handling
2182 @subsubsection Safe File Name Handling
2184 Here is how to make @code{find} output file names so that they can be
2185 used by other programs without being mangled or misinterpreted.  You
2186 can process file names generated this way by giving the @samp{-0} or
2187 @samp{--null} option to GNU @code{xargs}, GNU @code{tar}, GNU
2188 @code{cpio}, or @code{perl}.
2190 @deffn Action -print0
2191 True; print the entire file name on the standard output, followed by a
2192 null character.
2193 @end deffn
2195 @deffn Action -fprint0 file
2196 True; like @samp{-print0} but write to @var{file} like @samp{-fprint}
2197 (@pxref{Print File Name}).  The output file is always created.
2198 @end deffn
2200 As of findutils version 4.2.4, the @code{locate} program also has a
2201 @samp{--null} option which does the same thing.  For similarity with
2202 @code{xargs}, the short form of the option @samp{-0} can also be used.
2204 If you want to be able to handle file names safely but need to run
2205 commands which want to be connected to a terminal on their input, you
2206 can use the @samp{--arg-file} option to @code{xargs} like this:
2208 @example
2209 find / -name xyzzy -print0 > list
2210 xargs --null --arg-file=list munge
2211 @end example
2213 The example above runs the @code{munge} program on all the files named
2214 @file{xyzzy} that we can find, but @code{munge}'s input will still be
2215 the terminal (or whatever the shell was using as standard input).  If
2216 your shell has the ``process substitution'' feature @samp{<(...)}, you
2217 can do this in just one step:
2219 @example
2220 xargs --null --arg-file=<(find / -name xyzzy -print0) munge
2221 @end example
2223 @node Unusual Characters in File Names
2224 @subsubsection Unusual Characters in File Names
2225 As discussed above, you often need to be careful about how the names
2226 of files are handled by @code{find} and other programs.  If the output
2227 of @code{find} is not going to another program but instead is being
2228 shown on a terminal, this can still be a problem.  For example, some
2229 character sequences can reprogram the function keys on some terminals.
2230 @xref{Security Considerations}, for a discussion of other security
2231 problems relating to @code{find}.
2233 Unusual characters are handled differently by various
2234 actions, as described below.
2236 @table @samp
2237 @item -print0
2238 @itemx -fprint0
2239 Always print the exact file name, unchanged, even if the output is
2240 going to a terminal.
2241 @item -ok
2242 @itemx -okdir
2243 Always print the exact file name, unchanged.  This will probably
2244 change in a future release.
2245 @item -ls
2246 @itemx -fls
2247 Unusual characters are always escaped.  White space, backslash, and
2248 double quote characters are printed using C-style escaping (for
2249 example @samp{\f}, @samp{\"}).  Other unusual characters are printed
2250 using an octal escape.  Other printable characters (for @samp{-ls} and
2251 @samp{-fls} these are the characters between octal 041 and 0176) are
2252 printed as-is.
2253 @item -printf
2254 @itemx -fprintf
2255 If the output is not going to a terminal, it is printed as-is.
2256 Otherwise, the result depends on which directive is in use:
2258 @table @asis
2259 @item %D, %F, %H, %Y, %y
2260 These expand to values which are not under control of files' owners,
2261 and so are printed as-is.
2262 @item  %a, %b, %c, %d, %g, %G, %i, %k, %m, %M, %n, %s, %t, %u, %U
2263 These have values which are under the control of files' owners but
2264 which cannot be used to send arbitrary data to the terminal, and so
2265 these are printed as-is.
2266 @item %f, %h, %l, %p, %P
2267 The output of these directives is quoted if the output is going to a
2268 terminal.
2270 This quoting is performed in the same way as for GNU @code{ls}.  This
2271 is not the same quoting mechanism as the one used for @samp{-ls} and
2272 @samp{fls}.  If you are able to decide what format to use for the
2273 output of @code{find} then it is normally better to use @samp{\0} as a
2274 terminator than to use newline, as file names can contain white space
2275 and newline characters.
2276 @end table
2277 @item -print
2278 @itemx -fprint
2279 Quoting is handled in the same way as for the @samp{%p} directive of
2280 @samp{-printf} and @samp{-fprintf}.  If you are using @code{find} in a
2281 script or in a situation where the matched files might have arbitrary
2282 names, you should consider using @samp{-print0} instead of
2283 @samp{-print}.
2284 @end table
2287 The @code{locate} program quotes and escapes unusual characters in
2288 file names in the same way as @code{find}'s @samp{-print} action.
2290 The behaviours described above may change soon, as the treatment of
2291 unprintable characters is harmonised for @samp{-ls}, @samp{-fls},
2292 @samp{-print}, @samp{-fprint}, @samp{-printf} and @samp{-fprintf}.
2294 @node Limiting Command Size
2295 @subsubsection Limiting Command Size
2297 @code{xargs} gives you control over how many arguments it passes to
2298 the command each time it executes it.  By default, it uses up to
2299 @code{ARG_MAX} - 2k, or 128k, whichever is smaller, characters per
2300 command.  It uses as many lines and arguments as fit within that
2301 limit.  The following options modify those values.
2303 @table @code
2304 @item --no-run-if-empty
2305 @itemx -r
2306 If the standard input does not contain any nonblanks, do not run the
2307 command.  By default, the command is run once even if there is no
2308 input.  This option is a GNU extension.
2310 @item --max-lines@r{[}=@var{max-lines}@r{]}
2311 @itemx -L @var{max-lines}
2312 @itemx -l@r{[}@var{max-lines}@r{]}
2313 Use at most @var{max-lines} nonblank input lines per command line;
2314 @var{max-lines} defaults to 1 if omitted; omitting the argument is not
2315 allowed in the case of the @samp{-L} option.  Trailing blanks cause an
2316 input line to be logically continued on the next input line, for the
2317 purpose of counting the lines.  Implies @samp{-x}.  The preferred name
2318 for this option is @samp{-L} as this is specified by POSIX.  
2320 @item --max-args=@var{max-args}
2321 @itemx -n @var{max-args}
2322 Use at most @var{max-args} arguments per command line.  Fewer than
2323 @var{max-args} arguments will be used if the size (see the @samp{-s}
2324 option) is exceeded, unless the @samp{-x} option is given, in which
2325 case @code{xargs} will exit.
2327 @item --max-chars=@var{max-chars}
2328 @itemx -s @var{max-chars}
2329 Use at most @var{max-chars} characters per command line, including the
2330 command initial arguments and the terminating nulls at the ends of the
2331 argument strings.  If you specify a value for this option which is too
2332 large or small, a warning message is printed and the appropriate upper
2333 or lower limit is used instead.  You can use @samp{--show-limits}
2334 option to understand the command-line limits applying to @code{xargs}
2335 and how this is affected by any other options.
2337 @item --max-procs=@var{max-procs}
2338 @itemx -P @var{max-procs}
2339 Run up to @var{max-procs} processes at a time; the default is 1.  If
2340 @var{max-procs} is 0, @code{xargs} will run as many processes as
2341 possible at a time.  Use the @samp{-n}, @samp{-s}, or @samp{-L} option
2342 with @samp{-P}; otherwise chances are that the command will be run
2343 only once.
2344 @end table
2346 @node Interspersing File Names
2347 @subsubsection Interspersing File Names
2349 @code{xargs} can insert the name of the file it is processing between
2350 arguments you give for the command.  Unless you also give options to
2351 limit the command size (@pxref{Limiting Command Size}), this mode of
2352 operation is equivalent to @samp{find -exec} (@pxref{Single File}).
2354 @table @code
2355 @item --replace@r{[}=@var{replace-str}@r{]}
2356 @itemx -I @var{replace-str}
2357 @itemx -i @var{replace-str}
2358 Replace occurrences of @var{replace-str} in the initial arguments with
2359 names read from the input.  Also, unquoted blanks do not terminate
2360 arguments; instead, the input is split at newlines only.  For the
2361 @samp{-i} option, if @var{replace-str} is omitted for @samp{--replace}
2362 or @samp{-i}, it defaults to @samp{@{@}} (like for @samp{find -exec}).
2363 Implies @samp{-x} and @samp{-l 1}.  @samp{-i} is deprecated in favour
2364 of @samp{-I}. As an example, to sort each file in the @file{bills}
2365 directory, leaving the output in that file name with @file{.sorted}
2366 appended, you could do:
2368 @example
2369 find bills -type f | xargs -I XX sort -o XX.sorted XX
2370 @end example
2372 @noindent
2373 The equivalent command using @samp{find -execdir} is:
2375 @example
2376 find bills -type f -execdir sort -o '@{@}.sorted' '@{@}' ';'
2377 @end example
2378 @end table
2381 When you use the @samp{-I} option, each line read from the input is
2382 buffered internally.  This means that there is an upper limit on the
2383 length of input line that xargs will accept when used with the
2384 @samp{-I} option.  To work around this limitation, you can use the
2385 @samp{-s} option to increase the amount of buffer space that xargs
2386 uses, and you can also use an extra invocation of xargs to ensure that
2387 very long lines do not occur.  For example:
2389 @example
2390 somecommand | xargs -s 50000 echo | xargs -I '@{@}' -s 100000 rm '@{@}'
2391 @end example
2393 Here, the first invocation of @code{xargs} has no input line length
2394 limit because it doesn't use the @samp{-I} option. The second
2395 invocation of @code{xargs} does have such a limit, but we have ensured
2396 that the it never encounters a line which is longer than it can
2397 handle.  
2399 This is not an ideal solution.  Instead, the @samp{-I} option should
2400 not impose a line length limit (apart from any limit imposed by the
2401 operating system) and so one might consider this limitation to be a
2402 bug.  A better solution would be to allow @code{xargs -I} to
2403 automatically move to a larger value for the @samp{-s} option when
2404 this is needed.
2406 This sort of problem doesn't occur with the output of @code{find}
2407 because it emits just one filename per line.
2409 @node Querying
2410 @subsection Querying
2412 To ask the user whether to execute a command on a single file, you can
2413 use the @code{find} primary @samp{-okdir} instead of @samp{-execdir},
2414 and the @code{find} primary @samp{-ok} instead of @samp{-exec}:
2416 @deffn Action -okdir command ;
2417 Like @samp{-execdir} (@pxref{Single File}), but ask the user first (on
2418 the standard input); if the response does not start with @samp{y} or
2419 @samp{Y}, do not run the command, and return false.  If the command is
2420 run, its standard input is redirected from @file{/dev/null}.
2421 @end deffn
2423 @deffn Action -ok command ;
2424 This insecure variant of the @samp{-okdir} action is specified by
2425 POSIX.  The main difference is that the command is executed in the
2426 directory from which @code{find} was invoked, meaning that @samp{@{@}}
2427 is expanded to a relative path starting with the name of one of the
2428 starting directories, rather than just the basename of the matched
2429 file.  If the command is run, its standard input is redirected from
2430 @file{/dev/null}.
2431 @end deffn
2433 When processing multiple files with a single command, to query the
2434 user you give @code{xargs} the following option.  When using this
2435 option, you might find it useful to control the number of files
2436 processed per invocation of the command (@pxref{Limiting Command
2437 Size}).
2439 @table @code
2440 @item --interactive
2441 @itemx -p
2442 Prompt the user about whether to run each command line and read a line
2443 from the terminal.  Only run the command line if the response starts
2444 with @samp{y} or @samp{Y}.  Implies @samp{-t}.
2445 @end table
2447 @node Delete Files
2448 @section Delete Files
2450 @deffn Action -delete
2451 Delete files or directories; true if removal succeeded.  If the
2452 removal failed, an error message is issued.
2454 The use of the @samp{-delete} action on the command line automatically
2455 turns on the @samp{-depth} option (@pxref{find Expressions}).
2456 @end deffn
2458 @node Adding Tests
2459 @section Adding Tests
2461 You can test for file attributes that none of the @code{find} builtin
2462 tests check.  To do this, use @code{xargs} to run a program that
2463 filters a list of files printed by @code{find}.  If possible, use
2464 @code{find} builtin tests to pare down the list, so the program run by
2465 @code{xargs} has less work to do.  The tests builtin to @code{find}
2466 will likely run faster than tests that other programs perform.
2468 For reasons of efficiency it is often useful to limit the number of
2469 times an external program has to be run.  For this reason, it is often
2470 a good idea to implement ``extended'' tests by using @code{xargs}.
2472 For example, here is a way to print the names of all of the unstripped
2473 binaries in the @file{/usr/local} directory tree.  Builtin tests avoid
2474 running @code{file} on files that are not regular files or are not
2475 executable.
2477 @example
2478 find /usr/local -type f -perm /a=x | xargs file |
2479   grep 'not stripped' | cut -d: -f1
2480 @end example
2482 @noindent
2483 The @code{cut} program removes everything after the file name from the
2484 output of @code{file}.
2486 However, using @code{xargs} can present important security problems
2487 (@pxref{Security Considerations}).  These can be avoided by using
2488 @samp{-execdir}.  The @samp{-execdir} action is also a useful way of
2489 putting your own test in the middle of a set of other tests or actions
2490 for @code{find} (for example, you might want to use @samp{-prune}).
2492 @c Idea from Martin Weitzel.
2493 To place a special test somewhere in the middle of a @code{find}
2494 expression, you can use @samp{-execdir} (or, less securely,
2495 @samp{-exec}) to run a program that performs the test.  Because
2496 @samp{-execdir} evaluates to the exit status of the executed program,
2497 you can use a program (which can be a shell script) that tests for a
2498 special attribute and make it exit with a true (zero) or false
2499 (non-zero) status.  It is a good idea to place such a special test
2500 @emph{after} the builtin tests, because it starts a new process which
2501 could be avoided if a builtin test evaluates to false.
2503 Here is a shell script called @code{unstripped} that checks whether
2504 its argument is an unstripped binary file:
2506 @example
2507 #! /bin/sh
2508 file "$1" | grep -q "not stripped"
2509 @end example
2512 This script relies on the shell exiting with the status of
2513 the last command in the pipeline, in this case @code{grep}.  The
2514 @code{grep} command exits with a true status if it found any matches,
2515 false if not.  Here is an example of using the script (assuming it is
2516 in your search path).  It lists the stripped executables (and shell
2517 scripts) in the file @file{sbins} and the unstripped ones in
2518 @file{ubins}.
2520 @example
2521 find /usr/local -type f -perm /a=x \
2522   \( -execdir unstripped '@{@}' \; -fprint ubins -o -fprint sbins \)
2523 @end example
2526 @node Databases
2527 @chapter File Name Databases
2529 The file name databases used by @code{locate} contain lists of files
2530 that were in particular directory trees when the databases were last
2531 updated.  The file name of the default database is determined when
2532 @code{locate} and @code{updatedb} are configured and installed.  The
2533 frequency with which the databases are updated and the directories for
2534 which they contain entries depend on how often @code{updatedb} is run,
2535 and with which arguments.
2537 You can obtain some statistics about the databases by using
2538 @samp{locate --statistics}.
2540 @menu
2541 * Database Locations::
2542 * Database Formats::
2543 * Newline Handling::
2544 @end menu
2547 @node Database Locations
2548 @section Database Locations
2550 There can be multiple file name databases.  Users can select which
2551 databases @code{locate} searches using the @code{LOCATE_PATH}
2552 environment variable or a command line option.  The system
2553 administrator can choose the file name of the default database, the
2554 frequency with which the databases are updated, and the directories
2555 for which they contain entries.  File name databases are updated by
2556 running the @code{updatedb} program, typically nightly.
2558 In networked environments, it often makes sense to build a database at
2559 the root of each filesystem, containing the entries for that
2560 filesystem.  @code{updatedb} is then run for each filesystem on the
2561 fileserver where that filesystem is on a local disk, to prevent
2562 thrashing the network.
2564 @xref{Invoking updatedb},
2565 for the description of the options to @code{updatedb}, which specify
2566 which directories would each database contain entries for.
2569 @node Database Formats
2570 @section Database Formats
2572 The file name databases contain lists of files that were in particular
2573 directory trees when the databases were last updated.  The file name
2574 database format changed starting with GNU @code{locate} version 4.0 to
2575 allow machines with different byte orderings to share the databases.
2576 The new GNU @code{locate} can read both the old and new database
2577 formats.  However, old versions of @code{locate} and @code{find}
2578 produce incorrect results if given a new-format database.
2580 Support for the old database format will eventually be discontinued,
2581 first in @code{updatedb} and later in @code{xargs}.
2583 If you run @samp{locate --statistics}, the resulting summary indicates
2584 the type of each @code{locate} database.
2587 @menu
2588 * New Database Format::
2589 * Sample Database::
2590 * Old Database Format::
2591 @end menu
2593 @node New Database Format
2594 @subsection New Database Format
2596 @code{updatedb} runs a program called @code{frcode} to
2597 @dfn{front-compress} the list of file names, which reduces the
2598 database size by a factor of 4 to 5.  Front-compression (also known as
2599 incremental encoding) works as follows.
2601 The database entries are a sorted list (case-insensitively, for users'
2602 convenience).  Since the list is sorted, each entry is likely to share
2603 a prefix (initial string) with the previous entry.  Each database
2604 entry begins with an offset-differential count byte, which is the
2605 additional number of characters of prefix of the preceding entry to
2606 use beyond the number that the preceding entry is using of its
2607 predecessor.  (The counts can be negative.)  Following the count is a
2608 null-terminated ASCII remainder---the part of the name that follows
2609 the shared prefix.
2611 If the offset-differential count is larger than can be stored in a
2612 byte (+/-127), the byte has the value 0x80 and the count follows in a
2613 2-byte word, with the high byte first (network byte order).
2615 Every database begins with a dummy entry for a file called
2616 @file{LOCATE02}, which @code{locate} checks for to ensure that the
2617 database file has the correct format; it ignores the entry in doing
2618 the search.
2620 Databases cannot be concatenated together, even if the first (dummy)
2621 entry is trimmed from all but the first database.  This is because the
2622 offset-differential count in the first entry of the second and
2623 following databases will be wrong.
2625 In the output of @samp{locate --statistics}, the new database format
2626 is referred to as @samp{LOCATE02}.
2628 @node Sample Database
2629 @subsection Sample Database
2631 Sample input to @code{frcode}:
2632 @c with nulls changed to newlines:
2634 @example
2635 /usr/src
2636 /usr/src/cmd/aardvark.c
2637 /usr/src/cmd/armadillo.c
2638 /usr/tmp/zoo
2639 @end example
2641 Length of the longest prefix of the preceding entry to share:
2643 @example
2644 0 /usr/src
2645 8 /cmd/aardvark.c
2646 14 rmadillo.c
2647 5 tmp/zoo
2648 @end example
2650 Output from @code{frcode}, with trailing nulls changed to newlines
2651 and count bytes made printable:
2653 @example
2654 0 LOCATE02
2655 0 /usr/src
2656 8 /cmd/aardvark.c
2657 6 rmadillo.c
2658 -9 tmp/zoo
2659 @end example
2661 (6 = 14 - 8, and -9 = 5 - 14)
2663 @node Old Database Format
2664 @subsection Old Database Format
2666 The old database format is used by Unix @code{locate} and @code{find}
2667 programs and earlier releases of the GNU ones.  @code{updatedb}
2668 produces this format if given the @samp{--old-format} option.
2670 @code{updatedb} runs programs called @code{bigram} and @code{code} to
2671 produce old-format databases.  The old format differs from the new one
2672 in the following ways.  Instead of each entry starting with an
2673 offset-differential count byte and ending with a null, byte values
2674 from 0 through 28 indicate offset-differential counts from -14 through
2675 14.  The byte value indicating that a long offset-differential count
2676 follows is 0x1e (30), not 0x80.  The long counts are stored in host
2677 byte order, which is not necessarily network byte order, and host
2678 integer word size, which is usually 4 bytes.  They also represent a
2679 count 14 less than their value.  The database lines have no
2680 termination byte; the start of the next line is indicated by its first
2681 byte having a value <= 30.
2683 In addition, instead of starting with a dummy entry, the old database
2684 format starts with a 256 byte table containing the 128 most common
2685 bigrams in the file list.  A bigram is a pair of adjacent bytes.
2686 Bytes in the database that have the high bit set are indexes (with the
2687 high bit cleared) into the bigram table.  The bigram and
2688 offset-differential count coding makes these databases 20-25% smaller
2689 than the new format, but makes them not 8-bit clean.  Any byte in a
2690 file name that is in the ranges used for the special codes is replaced
2691 in the database by a question mark, which not coincidentally is the
2692 shell wildcard to match a single character.
2694 The old format therefore cannot faithfully store entries with
2695 non-ASCII characters. It therefore should not be used in
2696 internationalised environments.
2698 The output of @samp{locate --statistics} will give an incorrect count
2699 of the number of file names containing newlines or high-bit characters
2700 for old-format databases.
2702 @node Newline Handling
2703 @section Newline Handling
2705 Within the database, file names are terminated with a null character.
2706 This is the case for both the old and the new format.
2708 When the new database format is being used, the compression technique
2709 used to generate the database though relies on the ability to sort the
2710 list of files before they are presented to @code{frcode}.
2712 If the system's sort command allows its input list of files to be
2713 separated with null characters via the @samp{-z} option, this option
2714 is used and therefore @code{updatedb} and @code{locate} will both
2715 correctly handle file names containing newlines.  If the @code{sort}
2716 command lacks support for this, the list of files is delimited with
2717 the newline character, meaning that parts of file names containing
2718 newlines will be incorrectly sorted.  This can result in both
2719 incorrect matches and incorrect failures to match.
2721 On the other hand, if you are using the old database format, file
2722 names with embedded newlines are not correctly handled.  There is no
2723 technical limitation which enforces this, it's just that the
2724 @code{bigram} program has not been updated to support lists of file
2725 names separated by nulls.
2727 So, if you are using the new database format (this is the default) and
2728 your system uses GNU @code{sort}, newlines will be correctly handled
2729 at all times.  Otherwise, newlines may not be correctly handled.
2731 @node File Permissions
2732 @chapter File Permissions
2734 @include perm.texi
2736 @include getdate.texi
2738 @node Reference
2739 @chapter Reference
2741 Below are summaries of the command line syntax for the programs
2742 discussed in this manual.
2744 @menu
2745 * Invoking find::
2746 * Invoking locate::
2747 * Invoking updatedb::
2748 * Invoking xargs::
2749 * Regular Expressions::
2750 * Environment Variables::
2751 @end menu
2753 @node Invoking find
2754 @section Invoking @code{find}
2756 @example
2757 find @r{[-H] [-L] [-P] [-D @var{debugoptions}] [-O@var{level}]} @r{[}@var{file}@dots{}@r{]} @r{[}@var{expression}@r{]}
2758 @end example
2760 @code{find} searches the directory tree rooted at each file name
2761 @var{file} by evaluating the @var{expression} on each file it finds in
2762 the tree.
2764 The command line may begin with the @samp{-H}, @samp{-L}, @samp{-P},
2765 @samp{-D} and @samp{-O} options.  These are followed by a list of
2766 files or directories that should be searched.  If no files to search
2767 are specified, the current directory (@file{.}) is used.
2769 This list of files to search is followed by a list of expressions
2770 describing the files we wish to search for.  The first part of the
2771 expression is recognised by the fact that it begins with @samp{-}
2772 followed by some other letters (for example @samp{-print}), or is
2773 either @samp{(} or @samp{!}.  Any arguments after it are the rest of
2774 the expression.  
2776 If no expression is given, the expression @samp{-print} is used.
2778 The @code{find} command exits with status zero if all files matched
2779 are processed successfully, greater than zero if errors occur.
2781 The @code{find} program also recognises two options for administrative
2782 use:
2784 @table @samp
2785 @item --help
2786 Print a summary of the command line usage and exit.
2787 @item --version
2788 Print the version number of @code{find} and exit.
2789 @end table
2791 The @samp{-version} option is a synonym for @samp{--version}
2794 @menu
2795 * Filesystem Traversal Options::
2796 * Warning Messages::
2797 * Optimisation Options::
2798 * Debug Options::
2799 * Find Expressions::
2800 @end menu
2802 @node Filesystem Traversal Options
2803 @subsection Filesystem Traversal Options
2805 The options @samp{-H}, @samp{-L} or @samp{-P} may be specified at the
2806 start of the command line (if none of these is specified, @samp{-P} is
2807 assumed).  If you specify more than one of these options, the last one
2808 specified takes effect (but note that the @samp{-follow} option is
2809 equivalent to @samp{-L}).  
2811 @table @code
2812 @item -P
2813 Never follow symbolic links (this is the default), except in the case
2814 of the @samp{-xtype} predicate.
2815 @item -L
2816 Always follow symbolic links, except in the case of the @samp{-xtype}
2817 predicate.
2818 @item -H
2819 Follow symbolic links specified in the list of files to search, or
2820 which are otherwise specified on the command line.
2821 @end table
2823 If @code{find} would follow a symbolic link, but cannot for any reason
2824 (for example, because it has insufficient permissions or the link is
2825 broken), it falls back on using the properties of the symbolic link
2826 itself.  @ref{Symbolic Links} for a more complete description of how
2827 symbolic links are handled.
2829 @node Warning Messages
2830 @subsection Warning Messages
2832 If there is an error on the @code{find} command line, an error message
2833 is normally issued.  However, there are some usages that are
2834 inadvisable but which @code{find} should still accept.  Under these
2835 circumstances, @code{find} may issue a warning message.  By default,
2836 warnings are enabled only if @code{find} is being run interactively
2837 (specifically, if the standard input is a terminal).  Warning messages
2838 can be controlled explicitly by the use of options on the command
2839 line:
2841 @table @code
2842 @item -warn
2843 Issue warning messages where appropriate.
2844 @item -nowarn
2845 Do not issue warning messages.
2846 @end table
2848 These options take effect at the point on the command line where they
2849 are specified.  Therefore it's not useful to specify @samp{-nowarn} at
2850 the end of the command line.  The warning messages affected by the
2851 above options are triggered by:
2853 @itemize @minus
2854 @item
2855 Use of the @samp{-d} option which is deprecated; please use
2856 @samp{-depth} instead, since the latter is POSIX-compliant.
2857 @item
2858 Use of the @samp{-ipath} option which is deprecated; please use
2859 @samp{-iwholename} instead.
2860 @item
2861 Specifying an option (for example @samp{-mindepth}) after a non-option
2862 (for example @samp{-type} or @samp{-print}) on the command line.
2863 @end itemize
2865 The default behaviour above is designed to work in that way so that
2866 existing shell scripts don't generate spurious errors, but people will
2867 be made aware of the problem.
2869 Some warning messages are issued for less common or more serious
2870 problems, and consequently cannot be turned off:
2872 @itemize @minus
2873 @item
2874 Use of an unrecognised backslash escape sequence with @samp{-fprintf}
2875 @item
2876 Use of an unrecognised formatting directive with @samp{-fprintf}
2877 @end itemize
2879 @node Optimisation Options
2880 @subsection Optimisation Options
2882 The @samp{-O@var{level}} option sets @code{find}'s optimisation level
2883 to @var{level}.  The default optimisation level is 1.
2885 At certain optimisation levels, @code{find} reorders tests to speed up
2886 execution while preserving the overall effect; that is, predicates
2887 with side effects are not reordered relative to each other.  The
2888 optimisations performed at each optimisation level are as follows.
2890 @table @samp
2891 @item 0
2892 Currently equivalent to optimisation level 1.
2894 @item 1
2895 This is the default optimisation level and corresponds to the
2896 traditional behaviour.  Expressions are reordered so that tests based
2897 only on the names of files (for example@samp{ -name} and
2898 @samp{-regex}) are performed first.
2900 @item 2 
2901 Any @samp{-type} or @samp{-xtype} tests are performed after any tests
2902 based only on the names of files, but before any tests that require
2903 information from the inode.  On many modern versions of Unix, file
2904 types are returned by @code{readdir()} and so these predicates are
2905 faster to evaluate than predicates which need to stat the file first.
2907 @item 3 
2908 At this optimisation level, the full cost-based query optimiser is
2909 enabled.  The order of tests is modified so that cheap (i.e., fast)
2910 tests are performed first and more expensive ones are performed later,
2911 if necessary.  Within each cost band, predicates are evaluated earlier
2912 or later according to whether they are likely to succeed or not.  For
2913 @samp{-o}, predicates which are likely to succeed are evaluated
2914 earlier, and for @samp{-a}, predicates which are likely to fail are
2915 evaluated earlier.
2916 @end table
2919 @node Debug Options
2920 @subsection Debug Options
2922 The @samp{-D} option makes @code{find} produce diagnostic output.
2923 Much of the information is useful only for diagnosing problems, and so
2924 most people will not find this option helpful.
2926 The list of debug options should be comma separated.  Compatibility of
2927 the debug options is not guaranteed between releases of findutils.
2928 For a complete list of valid debug options, see the output of
2929 @code{find -D help}.  Valid debug options include:
2930 @table @samp
2931 @item help
2932 Explain the debugging options.
2933 @item tree   
2934 Show the expression tree in its original and optimised form.
2935 @item stat   
2936 Print messages as files are examined with the stat and lstat system
2937 calls.  The find program tries to minimise such calls.
2938 @item opt    
2939 Prints diagnostic information relating to the optimisation of the
2940 expression tree; see the @samp{-O} option.
2941 @end table
2943 @node Find Expressions
2944 @subsection Find Expressions
2946 The final part of the @code{find} command line is a list of
2947 expressions.  @xref{Primary Index}, for a summary of all of the tests,
2948 actions, and options that the expression can contain.  If the
2949 expression is missing, @samp{-print} is assumed.
2951 @node Invoking locate
2952 @section Invoking @code{locate}
2954 @example
2955 locate @r{[}@var{option}@dots{}@r{]} @var{pattern}@dots{}
2956 @end example
2958 For each @var{pattern} given @code{locate} searches one or more file
2959 name databases returning each match of @var{pattern}.
2961 For each @var{pattern} given @code{locate} searches one or more file
2962 name databases returning each match of @var{pattern}.
2964 @table @code
2965 @item --all
2966 @itemx -A
2967 Print only names which match all non-option arguments, not those
2968 matching one or more non-option arguments.
2970 @item --basename
2971 @itemx -b
2972 The specified pattern is matched against just the last component of
2973 the name of a file in the @code{locate} database.  This last
2974 component is also called the ``base name''.  For example, the base
2975 name of @file{/tmp/mystuff/foo.old.c} is @file{foo.old.c}.  If the
2976 pattern contains metacharacters, it must match the base name exactly.
2977 If not, it must match part of the base name.
2979 @item --count
2980 @itemx -c
2981 Instead of printing the matched file names, just print the total
2982 number of matches found, unless @samp{--print} (@samp{-p}) is also
2983 present.
2986 @item --database=@var{path}
2987 @itemx -d @var{path}
2988 Instead of searching the default @code{locate} database, @code{locate} search the file
2989 name databases in @var{path}, which is a colon-separated list of
2990 database file names.  You can also use the environment variable
2991 @code{LOCATE_PATH} to set the list of database files to search.  The
2992 option overrides the environment variable if both are used.  Empty
2993 elements in @var{path} (that is, a leading or trailing colon, or two
2994 colons in a row) are taken to stand for the default database.
2995 A database can be supplied on stdin, using @samp{-} as an element
2996 of @samp{path}. If more than one element of @samp{path} is @samp{-},
2997 later instances are ignored (but a warning message is printed).
2999 @item --existing
3000 @itemx -e
3001 Only print out such names which currently exist (instead of such names
3002 which existed when the database was created).  Note that this may slow
3003 down the program a lot, if there are many matches in the database.
3004 The way in which broken symbolic links are treated is affected by the
3005 @samp{-L}, @samp{-P} and @samp{-H} options.  Please note that it is
3006 possible for the file to be deleted after @code{locate} has checked
3007 that it exists, but before you use it.
3009 @item --non-existing
3010 @itemx -E
3011 Only print out such names which currently do not exist (instead of
3012 such names which existed when the database was created).  Note that
3013 this may slow down the program a lot, if there are many matches in the
3014 database.  The way in which broken symbolic links are treated is
3015 affected by the @samp{-L}, @samp{-P} and @samp{-H} options.  Please
3016 note that @code{locate} checks that the file does not exist, but a
3017 file of the same name might be created after @code{locate}'s check but
3018 before you read @code{locate}'s output.
3020 @item --follow
3021 @itemx -L
3022 If testing for the existence of files (with the @samp{-e} or @samp{-E}
3023 options), consider broken symbolic links to be non-existing.  This is
3024 the default behaviour.  
3026 @item --nofollow
3027 @itemx -P
3028 @itemx -H
3029 If testing for the existence of files (with the @samp{-e} or @samp{-E}
3030 options), treat broken symbolic links as if they were existing files.
3031 The @samp{-H} form of this option is provided purely for similarity
3032 with @code{find}; the use of @samp{-P} is recommended over @samp{-H}.
3034 @item --ignore-case
3035 @itemx -i
3036 Ignore case distinctions in both the pattern and the file names.
3038 @item --limit=N
3039 @itemx -l N
3040 Limit the number of results printed to N.  When used with the
3041 @samp{--count} option, the value printed will never be larger than
3042 this limit.
3043 @item --max-database-age=D
3044 Normally, @code{locate} will issue a warning message when it searches
3045 a database which is more than 8 days old.  This option changes that
3046 value to something other than 8.  The effect of specifying a negative
3047 value is undefined.
3048 @item --mmap
3049 @itemx -m
3050 Accepted but does nothing.  The option is supported only to provide
3051 compatibility with BSD's @code{locate}.
3053 @item --null
3054 @itemx -0
3055 Results are separated with the ASCII NUL character rather than the
3056 newline character.  To get the full benefit of the use of this option,
3057 use the new @code{locate} database format (that is the default
3058 anyway).
3060 @item --print
3061 @itemx -p
3062 Print search results when they normally would not, because of the
3063 presence of @samp{--statistics} (@samp{-S}) or @samp{--count}
3064 (@samp{-c}).
3066 @item --wholename
3067 @itemx -w
3068 The specified pattern is matched against the whole name of the file in
3069 the @code{locate} database.  If the pattern contains metacharacters,
3070 it must match exactly.  If not, it must match part of the whole file
3071 name.  This is the default behaviour.
3073 @item --regex
3074 @itemx -r
3075 Instead of using substring or shell glob matching, the pattern
3076 specified on the command line is understood to be a regular
3077 expression.  GNU Emacs-style regular expressions are assumed unless
3078 the @samp{--regextype} option is also given.  File names from the
3079 @code{locate} database are matched using the specified regular
3080 expression.  If the @samp{-i} flag is also given, matching is
3081 case-insensitive.  Matches are performed against the whole path name,
3082 and so by default a pathname will be matched if any part of it matches
3083 the specified regular expression.  The regular expression may use
3084 @samp{^} or @samp{$} to anchor a match at the beginning or end of a
3085 pathname.
3087 @item --regextype
3088 This option changes the regular expression syntax and behaviour used
3089 by the @samp{--regex} option.  @ref{Regular Expressions} for more
3090 information on the regular expression dialects understood by GNU
3091 findutils.
3093 @item --stdio
3094 @itemx -s
3095 Accepted but does nothing.  The option is supported only to provide
3096 compatibility with BSD's @code{locate}.
3098 @item --statistics
3099 @itemx -S
3100 Print some summary information for each @code{locate} database.  No
3101 search is performed unless non-option arguments are given.
3102 Although the BSD version of locate also has this option, the format of the
3103 output is different.
3105 @item --help
3106 Print a summary of the command line usage for @code{locate} and exit.
3108 @item --version
3109 Print the version number of @code{locate} and exit.
3110 @end table
3112 @node Invoking updatedb
3113 @section Invoking @code{updatedb}
3115 @example
3116 updatedb @r{[}@var{option}@dots{}@r{]}
3117 @end example
3119 @code{updatedb} creates and updates the database of file names used by
3120 @code{locate}.  @code{updatedb} generates a list of files similar to
3121 the output of @code{find} and then uses utilities for optimizing the
3122 database for performance.  @code{updatedb} is often run periodically
3123 as a @code{cron} job and configured with environment variables or
3124 command options.  Typically, operating systems have a shell script
3125 that ``exports'' configurations for variable definitions and uses
3126 another shell script that ``sources'' the configuration file into the
3127 environment and then executes @code{updatedb} in the environment.
3129 @code{updatedb} creates and updates the database of file names used by
3130 @code{locate}.  @code{updatedb} generates a list of files similar to
3131 the output of @code{find} and then uses utilities for optimizing the
3132 database for performance.  @code{updatedb} is often run periodically
3133 as a @code{cron} job and configured with environment variables or
3134 command options.  Typically, operating systems have a shell script
3135 that ``exports'' configurations for variable definitions and uses
3136 another shell script that ``sources'' the configuration file into the
3137 environment and then executes @code{updatedb} in the environment.
3139 @table @code
3140 @item --findoptions='@var{OPTION}@dots{}'
3141 Global options to pass on to @code{find}.
3142 The environment variable @code{FINDOPTIONS} also sets this value.
3143 Default is none.
3145 @item --localpaths='@var{path}@dots{}'
3146 Non-network directories to put in the database.
3147 Default is @file{/}.
3149 @item --netpaths='@var{path}@dots{}'
3150 Network (NFS, AFS, RFS, etc.) directories to put in the database.
3151 The environment variable @code{NETPATHS} also sets this value.
3152 Default is none.
3154 @item --prunepaths='@var{path}@dots{}'
3155 Directories to omit from the database, which would otherwise be
3156 included.  The environment variable @code{PRUNEPATHS} also sets this
3157 value.  Default is @file{/tmp /usr/tmp /var/tmp /afs}.  The paths are
3158 used as regular expressions (with @code{find ... -regex}, so you need
3159 to specify these paths in the same way that @code{find} will encounter
3160 them.  This means for example that the paths must not include trailing
3161 slashes.
3163 @item --prunefs='@var{path}@dots{}'
3164 Filesystems to omit from the database, which would otherwise be
3165 included.  Note that files are pruned when a filesystem is reached;
3166 Any filesystem mounted under an undesired filesystem will be ignored.
3167 The environment variable @code{PRUNEFS} also sets this value.  Default
3168 is @file{nfs NFS proc}.
3170 @item --output=@var{dbfile}
3171 The database file to build.  Default is system-dependent, but
3172 typically @file{/usr/local/var/locatedb}.
3174 @item --localuser=@var{user}
3175 The user to search the non-network directories as, using @code{su}.
3176 Default is to search the non-network directories as the current user.
3177 You can also use the environment variable @code{LOCALUSER} to set this user.
3179 @item --netuser=@var{user}
3180 The user to search network directories as, using @code{su}.  Default
3181 @code{user} is @code{daemon}.  You can also use the environment variable
3182 @code{NETUSER} to set this user.
3184 @item --old-format
3185 Generate a @code{locate} database in the old format, for compatibility
3186 with versions of @code{locate} other than GNU @code{locate}.  Using
3187 this option means that @code{locate} will not be able to properly
3188 handle non-ASCII characters in file names (that is, file names
3189 containing characters which have the eighth bit set, such as many of
3190 the characters from the ISO-8859-1 character set).
3191 @item --help
3192 Print a summary of the command line usage and exit.
3193 @item --version
3194 Print the version number of @code{updatedb} and exit.
3195 @end table
3197 @node Invoking xargs
3198 @section Invoking @code{xargs}
3200 @example
3201 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
3202 @end example
3204 @code{xargs} exits with the following status:
3206 @table @asis
3207 @item 0
3208 if it succeeds
3209 @item 123
3210 if any invocation of the command exited with status 1-125
3211 @item 124
3212 if the command exited with status 255
3213 @item 125
3214 if the command is killed by a signal
3215 @item 126
3216 if the command cannot be run
3217 @item 127
3218 if the command is not found
3219 @item 1
3220 if some other error occurred.
3221 @end table
3223 Exit codes greater than 128 are used by the shell to indicate that 
3224 a program died due to a fatal signal.
3225   
3226 @table @code
3227 @item --arg-file@r{=@var{inputfile}}
3228 @itemx -a o@r{@var{inputfile}}
3229 Read names from the file @var{inputfile} instead of standard input.
3230 If you use this option, the standard input stream remains unchanged
3231 when commands are run. Otherwise, stdin is redirected from
3232 @file{/dev/null}.
3234 @item --null
3235 @itemx -0
3236 Input file names are terminated by a null character instead of by
3237 whitespace, and any quotes and backslash characters are not considered
3238 special (every character is taken literally).  Disables the end of
3239 file string, which is treated like any other argument.
3241 @item --delimiter @var{delim}
3242 @itemx -d @var{delim}
3244 Input file names are terminated by the specified character @var{delim}
3245 instead of by whitespace, and any quotes and backslash characters are
3246 not considered special (every character is taken literally).  Disables
3247 the end of file string, which is treated like any other argument.
3249 The specified delimiter may be a single character, a C-style character
3250 escape such as @samp{\n}, or an octal or hexadecimal escape code.
3251 Octal and hexadecimal escape codes are understood as for the
3252 @code{printf} command.  Multibyte characters are not supported.
3255 @item -E @var{eof-str}
3256 @itemx --eof@r{[}=@var{eof-str}@r{]}
3257 @itemx -e@r{[}@var{eof-str}@r{]}
3258 Set the end of file string to @var{eof-str}.  If the end of file
3259 string occurs as a line of input, the rest of the input is ignored.
3260 If @var{eof-str} is omitted (@samp{-e}) or blank (either @samp{-e} or
3261 @samp{-E}), there is no end of file string.  The @samp{-e} form of
3262 this option is deprecated in favour of the POSIX-compliant @samp{-E}
3263 option, which you should use instead.  As of GNU xargs version 4.2.9,
3264 the default behaviour of xargs is not to have a logical end-of-file
3265 marker.  The POSIX standard (IEEE Std 1003.1, 2004 Edition) allows
3266 this.
3268 @item --help
3269 Print a summary of the options to @code{xargs} and exit.
3271 @item -I @var{replace-str}
3272 @itemx --replace@r{[}=@var{replace-str}@r{]}
3273 @itemx -i@r{[}@var{replace-str}@r{]}
3274 Replace occurrences of @var{replace-str} in the initial arguments with
3275 names read from standard input.  Also, unquoted blanks do not
3276 terminate arguments; instead, the input is split at newlines only.  If
3277 @var{replace-str} is omitted (omitting it is allowed only for
3278 @samp{-i}), it defaults to @samp{@{@}} (like for @samp{find -exec}).
3279 Implies @samp{-x} and @samp{-l 1}.  The @samp{-i} option is deprecated
3280 in favour of the @samp{-I} option.
3282 @item -L @var{max-lines}
3283 @itemx --max-lines@r{[}=@var{max-lines}@r{]}
3284 @itemx -l@r{[}@var{max-lines}@r{]}
3285 Use at most @var{max-lines} non-blank input lines per command line.
3286 For @samp{-l}, @var{max-lines} defaults to 1 if omitted.  For
3287 @samp{-L}, the argument is mandatory.  Trailing blanks cause an input
3288 line to be logically continued on the next input line, for the purpose
3289 of counting the lines.  Implies @samp{-x}.  The @samp{-l} form of this
3290 option is deprecated in favour of the POSIX-compliant @samp{-L}
3291 option.
3293 @item --max-args=@var{max-args}
3294 @itemx -n @var{max-args}
3295 Use at most @var{max-args} arguments per command line.  Fewer than
3296 @var{max-args} arguments will be used if the size (see the @samp{-s}
3297 option) is exceeded, unless the @samp{-x} option is given, in which
3298 case @code{xargs} will exit.
3300 @item --interactive
3301 @itemx -p
3302 Prompt the user about whether to run each command line and read a line
3303 from the terminal.  Only run the command line if the response starts
3304 with @samp{y} or @samp{Y}.  Implies @samp{-t}.
3306 @item --no-run-if-empty
3307 @itemx -r
3308 If the standard input is completely empty, do not run the
3309 command.  By default, the command is run once even if there is no
3310 input.
3312 @item --max-chars=@var{max-chars}
3313 @itemx -s @var{max-chars}
3314 Use at most @var{max-chars} characters per command line, including the
3315 command, initial arguments and any terminating nulls at the ends of
3316 the argument strings.
3318 @item --show-limits
3319 Display the limits on the command-line length which are imposed by the
3320 operating system, @code{xargs}' choice of buffer size and the
3321 @samp{-s} option.  Pipe the input from @file{/dev/null} (and perhaps
3322 specify @samp{--no-run-if-empty}) if you don't want @code{xargs} to do
3323 anything.
3325 @item --verbose
3326 @itemx -t
3327 Print the command line on the standard error output before executing
3330 @item --version
3331 Print the version number of @code{xargs} and exit.
3333 @item --exit
3334 @itemx -x
3335 Exit if the size (see the @samp{-s} option) is exceeded.
3338 @item --max-procs=@var{max-procs}
3339 @itemx -P @var{max-procs}
3340 Run simultaneously up to @var{max-procs} processes at once; the default is 1.  If
3341 @var{max-procs} is 0, @code{xargs} will run as many processes as
3342 possible simultaneously.
3343 @end table
3346 @node Regular Expressions
3347 @section Regular Expressions
3349 The @samp{-regex} and @samp{-iregex} tests of @code{find} allow
3350 matching by regular expression, as does the @samp{--regex} option of
3351 @code{locate}.  There are many different types of Regular Expression,
3352 but the type used by @code{find} and @code{locate} is the same as is
3353 used in GNU Emacs.  Both programs provide an option which allows you
3354 to select an alternative regular expression syntax; for @code{find}
3355 this is the @samp{-regextype} option, and for @code{locate} this is
3356 the @samp{--regextype} option.
3358 These options take a single argument, which indicates the specific
3359 regular expression syntax and behaviour that should be used.  This
3360 should be one of the following:
3362 @include regexprops.texi
3364 @node Environment Variables
3365 @section Environment Variables
3366 @table @var
3367 @item LANG
3368 Provides a default value for the internationalisation variables that
3369 are unset or null.
3370 @item LC_ALL
3371 If set to a non-empty string value, override the values of all the
3372 other internationalisation variables.
3373 @item LC_COLLATE
3374 The POSIX standard specifies that this variable affects the pattern
3375 matching to be used for the `\-name' option.  GNU find uses the
3376 GNU version of the @code{fnmatch} library function.
3378 POSIX also specifies that the `LC_COLLATE' environment 
3379 variable affects the interpretation of the user's response to the 
3380 query issued by `\-ok', but this is not the case for GNU find.
3381 @item LC_CTYPE 
3382 This variable affects the treatment of character classes used with 
3383 the @samp{-name} test, if the system's 
3384 @code{fnmatch} library function supports this.   It has no effect on the behaviour 
3385 of the @samp{-ok} expression.
3386 @item LC_MESSAGES
3387 Determines the locale to be used for internationalised messages.
3388 @item NLSPATH
3389 Determines the location of the internationalisation message catalogues.
3390 @item PATH
3391 Affects the directories which are searched to find the executables
3392 invoked by @samp{-exec}, @samp{-execdir} @samp{-ok} and @samp{-okdir}.
3393 If the @var{PATH} environment variable includes the current directory
3394 (by explicitly including @samp{.} or by having an empty element), and
3395 the find command line includes @samp{-execdir} or @samp{-okdir},
3396 @code{find} will refuse to run.  @xref{Security Considerations}, for a
3397 more detailed discussion of security matters.
3399 @item POSIXLY_CORRECT 
3400 Determines the block size used by @samp{-ls} and @samp{-fls}.  
3401 If @var{POSIXLY_CORRECT} is set, blocks are units of 512 bytes.  Otherwise
3402 they are units of 1024 bytes.
3404 @item TZ 
3405 Affects the time zone used for some of the time-related format
3406 directives of @samp{-printf} and @samp{-fprintf}.
3407 @end table
3411 @node Common Tasks
3412 @chapter Common Tasks
3414 The sections that follow contain some extended examples that both give
3415 a good idea of the power of these programs, and show you how to solve
3416 common real-world problems.
3418 @menu
3419 * Viewing And Editing::
3420 * Archiving::
3421 * Cleaning Up::
3422 * Strange File Names::
3423 * Fixing Permissions::
3424 * Classifying Files::
3425 @end menu
3427 @node Viewing And Editing
3428 @section Viewing And Editing
3430 To view a list of files that meet certain criteria, simply run your
3431 file viewing program with the file names as arguments.  Shells
3432 substitute a command enclosed in backquotes with its output, so the
3433 whole command looks like this:
3435 @example
3436 less `find /usr/include -name '*.h' | xargs grep -l mode_t`
3437 @end example
3439 @noindent
3440 You can edit those files by giving an editor name instead of a file
3441 viewing program:
3443 @example
3444 emacs `find /usr/include -name '*.h' | xargs grep -l mode_t`
3445 @end example
3447 Because there is a limit to the length of any individual command line,
3448 there is a limit to the number of files that can be handled in this
3449 way.  We can get around this difficulty by using xargs like this:
3451 @example
3452 find /usr/include -name '*.h' | xargs grep -l mode_t > todo
3453 xargs --arg-file=todo emacs
3454 @end example
3456 Here, @code{xargs} will run @code{emacs} as many times as necessary to
3457 visit all of the files listed in the file @file{todo}.
3459 @node Archiving
3460 @section Archiving
3462 You can pass a list of files produced by @code{find} to a file
3463 archiving program.  GNU @code{tar} and @code{cpio} can both read lists
3464 of file names from the standard input---either delimited by nulls (the
3465 safe way) or by blanks (the lazy, risky default way).  To use
3466 null-delimited names, give them the @samp{--null} option.  You can
3467 store a file archive in a file, write it on a tape, or send it over a
3468 network to extract on another machine.
3470 One common use of @code{find} to archive files is to send a list of
3471 the files in a directory tree to @code{cpio}.  Use @samp{-depth} so if
3472 a directory does not have write permission for its owner, its contents
3473 can still be restored from the archive since the directory's
3474 permissions are restored after its contents.  Here is an example of
3475 doing this using @code{cpio}; you could use a more complex @code{find}
3476 expression to archive only certain files.
3478 @example
3479 find . -depth -print0 |
3480   cpio --create --null --format=crc --file=/dev/nrst0
3481 @end example
3483 You could restore that archive using this command:
3485 @example
3486 cpio --extract --null --make-dir --unconditional \
3487   --preserve --file=/dev/nrst0
3488 @end example
3490 Here are the commands to do the same things using @code{tar}:
3492 @example
3493 find . -depth -print0 |
3494   tar --create --null --files-from=- --file=/dev/nrst0
3496 tar --extract --null --preserve-perm --same-owner \
3497   --file=/dev/nrst0
3498 @end example
3500 @c Idea from Rick Sladkey.
3501 Here is an example of copying a directory from one machine to another:
3503 @example
3504 find . -depth -print0 | cpio -0o -Hnewc |
3505   rsh @var{other-machine} "cd `pwd` && cpio -i0dum"
3506 @end example
3508 @node Cleaning Up
3509 @section Cleaning Up
3511 @c Idea from Jim Meyering.
3512 This section gives examples of removing unwanted files in various
3513 situations.  Here is a command to remove the CVS backup files created
3514 when an update requires a merge:
3516 @example
3517 find . -name '.#*' -print0 | xargs -0r rm -f
3518 @end example
3520 The command above works, but the following is safer:
3522 @example
3523 find . -name '.#*' -depth -delete
3524 @end example
3526 @c Idea from Franc,ois Pinard.
3527 You can run this command to clean out your clutter in @file{/tmp}.
3528 You might place it in the file your shell runs when you log out
3529 (@file{.bash_logout}, @file{.logout}, or @file{.zlogout}, depending on
3530 which shell you use).
3532 @example
3533 find /tmp -depth -user "$LOGNAME" -type f -delete
3534 @end example
3536 If your @code{find} command removes directories, you may find that
3537 you get a spurious error message when @code{find} tries to recurse
3538 into a directory that has now been removed.  Using the @samp{-depth}
3539 option will normally resolve this problem.
3541 @c Idea from Noah Friedman.
3542 To remove old Emacs backup and auto-save files, you can use a command
3543 like the following.  It is especially important in this case to use
3544 null-terminated file names because Emacs packages like the VM mailer
3545 often create temporary file names with spaces in them, like
3546 @file{#reply to David J. MacKenzie<1>#}.
3548 @example
3549 find ~ \( -name '*~' -o -name '#*#' \) -print0 |
3550   xargs --no-run-if-empty --null rm -vf
3551 @end example
3553 Removing old files from @file{/tmp} is commonly done from @code{cron}:
3555 @c Idea from Kaveh Ghazi.
3556 @example
3557 find /tmp /var/tmp -not -type d -mtime +3 -delete
3558 find /tmp /var/tmp -depth -mindepth 1 -type d -empty -delete
3559 @end example
3561 The second @code{find} command above uses @samp{-depth} so it cleans
3562 out empty directories depth-first, hoping that the parents become
3563 empty and can be removed too.  It uses @samp{-mindepth} to avoid
3564 removing @file{/tmp} itself if it becomes totally empty.
3566 @node Strange File Names
3567 @section Strange File Names
3569 @c Idea from:
3570 @c From: tmatimar@isgtec.com (Ted Timar)
3571 @c Newsgroups: comp.unix.questions,comp.unix.shell,comp.answers,news.answers
3572 @c Subject: Unix - Frequently Asked Questions (2/7) [Frequent posting]
3573 @c Subject: How do I remove a file with funny characters in the filename ?
3574 @c Date: Thu Mar 18 17:16:55 EST 1993
3575 @code{find} can help you remove or rename a file with strange
3576 characters in its name.  People are sometimes stymied by files whose
3577 names contain characters such as spaces, tabs, control characters, or
3578 characters with the high bit set.  The simplest way to remove such
3579 files is:
3581 @example
3582 rm -i @var{some*pattern*that*matches*the*problem*file}
3583 @end example
3585 @code{rm} asks you whether to remove each file matching the given
3586 pattern.  If you are using an old shell, this approach might not work
3587 if the file name contains a character with the high bit set; the shell
3588 may strip it off.  A more reliable way is:
3590 @example
3591 find . -maxdepth 1 @var{tests} -okdir rm '@{@}' \;
3592 @end example
3594 @noindent
3595 where @var{tests} uniquely identify the file.  The @samp{-maxdepth 1}
3596 option prevents @code{find} from wasting time searching for the file
3597 in any subdirectories; if there are no subdirectories, you may omit
3598 it.  A good way to uniquely identify the problem file is to figure out
3599 its inode number; use
3601 @example
3602 ls -i
3603 @end example
3605 Suppose you have a file whose name contains control characters, and
3606 you have found that its inode number is 12345.  This command prompts
3607 you for whether to remove it:
3609 @example
3610 find . -maxdepth 1 -inum 12345 -okdir rm -f '@{@}' \;
3611 @end example
3613 If you don't want to be asked, perhaps because the file name may
3614 contain a strange character sequence that will mess up your screen
3615 when printed, then use @samp{-execdir} instead of @samp{-okdir}.
3617 If you want to rename the file instead, you can use @code{mv} instead
3618 of @code{rm}:
3620 @example
3621 find . -maxdepth 1 -inum 12345 -okdir mv '@{@}' @var{new-file-name} \;
3622 @end example
3624 @node Fixing Permissions
3625 @section Fixing Permissions
3627 Suppose you want to make sure that everyone can write to the
3628 directories in a certain directory tree.  Here is a way to find
3629 directories lacking either user or group write permission (or both),
3630 and fix their permissions:
3632 @example
3633 find . -type d -not -perm -ug=w | xargs chmod ug+w
3634 @end example
3636 @noindent
3637 You could also reverse the operations, if you want to make sure that
3638 directories do @emph{not} have world write permission.
3640 @node Classifying Files
3641 @section Classifying Files
3643 @c Idea from:
3644 @c From: martin@mwtech.UUCP (Martin Weitzel)
3645 @c Newsgroups: comp.unix.wizards,comp.unix.questions
3646 @c Subject: Advanced usage of 'find' (Re: Unix security automating script)
3647 @c Date: 22 Mar 90 15:05:19 GMT
3648 If you want to classify a set of files into several groups based on
3649 different criteria, you can use the comma operator to perform multiple
3650 independent tests on the files.  Here is an example:
3652 @example
3653 find / -type d \( -perm -o=w -fprint allwrite , \
3654   -perm -o=x -fprint allexec \)
3656 echo "Directories that can be written to by everyone:"
3657 cat allwrite
3658 echo ""
3659 echo "Directories with search permissions for everyone:"
3660 cat allexec
3661 @end example
3663 @code{find} has only to make one scan through the directory tree
3664 (which is one of the most time consuming parts of its work).
3666 @node Worked Examples
3667 @chapter Worked Examples
3669 The tools in the findutils package, and in particular @code{find},
3670 have a large number of options.  This means that quite often,
3671 there is more than one way to do things.  Some of the options
3672 and facilities only exist for compatibility with other tools, and
3673 findutils provides improved ways of doing things.
3675 This chapter describes a number of useful tasks that are commonly
3676 performed, and compares the different ways of achieving them.
3678 @menu
3679 * Deleting Files::
3680 * Updating A Timestamp File::
3681 @end menu
3683 @node Deleting Files
3684 @section Deleting Files
3686 One of the most common tasks that @code{find} is used for is locating
3687 files that can be deleted.  This might include:
3689 @itemize
3690 @item 
3691 Files last modified more than 3 years ago which haven't been accessed
3692 for at least 2 years
3693 @item
3694 Files belonging to a certain user
3695 @item
3696 Temporary files which are no longer required
3697 @end itemize
3699 This example concentrates on the actual deletion task rather than on
3700 sophisticated ways of locating the files that need to be deleted.
3701 We'll assume that the files we want to delete are old files underneath
3702 @file{/var/tmp/stuff}.
3704 @subsection The Traditional Way
3706 The traditional way to delete files in @file{var/tmp/stuff} that have
3707 not been modified in over 90 days would have been:
3709 @smallexample
3710 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \;
3711 @end smallexample
3713 The above command uses @samp{-exec} to run the @code{/bin/rm} command
3714 to remove each file.  This approach works and in fact would have
3715 worked in Version 7 Unix in 1979.  However, there are a number of
3716 problems with this approach.
3719 The most obvious problem with the approach above is that it causes
3720 @code{find} to fork every time it finds a file that needs to delete,
3721 and the child process then has to use the @code{exec} system call to
3722 launch @code{/bin/rm}.   All this is quite inefficient.  If we are
3723 going to use @code{/bin/rm} to do this job, it is better to make it
3724 delete more than one file at a time.  
3726 The most obvious way of doing this is to use the shell's command
3727 expansion feature:
3729 @smallexample
3730 /bin/rm `find /var/tmp/stuff -mtime +90 -print`
3731 @end smallexample
3732 or you could use the more modern form
3733 @smallexample
3734 /bin/rm $(find /var/tmp/stuff -mtime +90 -print)
3735 @end smallexample
3737 The commands above are much more efficient than the first attempt.
3738 However, there is a problem with them.  The shell has a maximum
3739 command length which is imposed by the operating system (the actual
3740 limit varies between systems).  This means that while the command
3741 expansion technique will usually work, it will suddenly fail when
3742 there are lots of files to delete.  Since the task is to delete
3743 unwanted files, this is precisely the time we don't want things to go
3744 wrong.
3746 @subsection Making Use of xargs
3748 So, is there a way to be more efficient in the use of @code{fork()}
3749 and @code{exec()} without running up against this limit?
3750 Yes, we can be almost optimally efficient by making use
3751 of the @code{xargs} command.  The @code{xargs} command reads arguments
3752 from its standard input and builds them into command lines.  We can
3753 use it like this:
3755 @smallexample
3756 find /var/tmp/stuff -mtime +90 -print | xargs /bin/rm 
3757 @end smallexample
3759 For example if the files found by @code{find} are
3760 @file{/var/tmp/stuff/A}, 
3761 @file{/var/tmp/stuff/B} and 
3762 @file{/var/tmp/stuff/C} then @code{xargs} might issue the commands 
3764 @smallexample
3765 /bin/rm /var/tmp/stuff/A /var/tmp/stuff/B
3766 /bin/rm /var/tmp/stuff/C
3767 @end smallexample
3769 The above assumes that @code{xargs} has a very small maximum command
3770 line length.  The real limit is much larger but the idea is that
3771 @code{xargs} will run @code{/bin/rm} as many times as necessary to get
3772 the job done, given the limits on command line length.
3774 This usage of @code{xargs} is pretty efficient, and the @code{xargs}
3775 command is widely implemented (all modern versions of Unix offer it).
3776 So far then, the news is all good.  However, there is bad news too.
3778 @subsection Unusual characters in filenames
3780 Unix-like systems allow any characters to appear in file names with
3781 the exception of the ASCII NUL character and the backslash.
3782 Backslashes can occur in path names (as the directory separator) but
3783 not in the names of actual directory entries.  This means that the
3784 list of files that @code{xargs} reads could in fact contain white space
3785 characters --- spaces, tabs and newline characters.  Since by default,
3786 @code{xargs} assumes that the list of files it is reading uses white
3787 space as an argument separator, it cannot correctly handle the case
3788 where a filename actually includes white space.  This makes the
3789 default behaviour of @code{xargs} almost useless for handling
3790 arbitrary data.
3792 To solve this problem, GNU findutils introduced the @samp{-print0}
3793 action for @code{find}.  This uses the ASCII NUL character to separate
3794 the entries in the file list that it produces.  This is the ideal
3795 choice of separator since it is the only character that cannot appear
3796 within a path name.  The @samp{-0} option to @code{xargs} makes it
3797 assume that arguments are separated with ASCII NUL instead of white
3798 space.  It also turns off another misfeature in the default behaviour
3799 of @code{xargs}, which is that it pays attention to quote characters
3800 in its input.  Some versions of @code{xargs} also terminate when they
3801 see a lone @samp{_} in the input, but GNU @code{find} no longer does
3802 that (since it has become an optional behaviour in the Unix standard).
3804 So, putting @code{find -print0} together with @code{xargs -0} we get
3805 this command:
3807 @smallexample
3808 find /var/tmp/stuff -mtime +90 -print0 | xargs -0 /bin/rm 
3809 @end smallexample
3811 The result is an efficient way of proceeding that
3812 correctly handles all the possible characters that could appear in the
3813 list of files to delete.  This is good news.  However, there is, as
3814 I'm sure you're expecting, also more bad news.  The problem is that
3815 this is not a portable construct; although other versions of Unix
3816 (notable BSD-derived ones) support @samp{-print0}, it's not
3817 universal.  So, is there a more universal mechanism?
3819 @subsection Going back to -exec
3821 There is indeed a more universal mechanism, which is a slight
3822 modification to the @samp{-exec} action.  The normal @samp{-exec}
3823 action assumes that the command to run is terminated with a semicolon
3824 (the semicolon normally has to be quoted in order to protect it from
3825 interpretation as the shell command separator).  The SVR4 edition of
3826 Unix introduced a slight variation, which involves terminating the
3827 command with @samp{+} instead:
3829 @smallexample
3830 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \+
3831 @end smallexample
3833 The above use of @samp{-exec} causes @code{find} to build up a long
3834 command line and then issue it.  This can be less efficient than some
3835 uses of @code{xargs}; for example @code{xargs} allows new command
3836 lines to be built up while the previous command is still executing, and
3837 allows you to specify a number of commands to run in parallel.
3838 However, the @code{find @dots{} -exec @dots{} +} construct has the advantage
3839 of wide portability.  GNU findutils did not support @samp{-exec @dots{} +}
3840 until version 4.2.12; one of the reasons for this is that it already
3841 had the @samp{-print0} action in any case.
3844 @subsection A more secure version of -exec
3846 The command above seems to be efficient and portable.  However,
3847 within it lurks a security problem.  The problem is shared with
3848 all the commands we've tried in this worked example so far, too.  The
3849 security problem is a race condition; that is, if it is possible for
3850 somebody to manipulate the filesystem that you are searching while you
3851 are searching it, it is possible for them to persuade your @code{find}
3852 command to cause the deletion of a file that you can delete but they
3853 normally cannot.  
3855 The problem occurs because the @samp{-exec} action is defined by the
3856 @acronym{POSIX} standard to invoke its command with the same working directory
3857 as @code{find} had when it was started.  This means that the arguments
3858 which replace the @{@} include a relative path from @code{find}'s
3859 starting point down the file that needs to be deleted.  For example,
3861 @smallexample
3862 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \+
3863 @end smallexample
3865 might actually issue the command:
3867 @smallexample
3868 /bin/rm /var/tmp/stuff/A /var/tmp/stuff/B /var/tmp/stuff/passwd
3869 @end smallexample
3871 Notice the file @file{/var/tmp/stuff/passwd}.  Likewise, the command:
3873 @smallexample
3874 cd /var/tmp && find stuff -mtime +90 -exec /bin/rm @{@} \+
3875 @end smallexample
3877 might actually issue the command:
3879 @smallexample
3880 /bin/rm stuff/A stuff/B stuff/passwd
3881 @end smallexample
3883 If an attacker can rename @file{stuff} to something else (making use
3884 of their write permissions in @file{/var/tmp}) they can replace it
3885 with a symbolic link to @file{/etc}.  That means that the
3886 @code{/bin/rm} command will be invoked on @file{/etc/passwd}.  If you
3887 are running your @code{find} command as root, the attacker has just managed
3888 to delete a vital file.  All they needed to do to achieve this was
3889 replace a subdirectory with a symbolic link at the vital moment.
3891 There is however, a simple solution to the problem.  This is an action
3892 which works a lot like @code{-exec} but doesn't need to traverse a
3893 chain of directories to reach the file that it needs to work on.  This
3894 is the @samp{-execdir} action, which was introduced by the BSD family
3895 of operating systems.   The command,
3897 @smallexample
3898 find /var/tmp/stuff -mtime +90 -execdir /bin/rm @{@} \+
3899 @end smallexample
3901 might delete a set of files by performing these actions:
3903 @enumerate
3904 @item 
3905 Change directory to /var/tmp/stuff/foo
3906 @item 
3907 Invoke @code{/bin/rm ./file1 ./file2 ./file3}
3908 @item
3909 Change directory to /var/tmp/stuff/bar
3910 @item 
3911 Invoke @code{/bin/rm ./file99 ./file100 ./file101}
3912 @end enumerate
3914 This is a much more secure method.  We are no longer exposed to a race
3915 condition.  For many typical uses of @code{find}, this is the best
3916 strategy.   It's reasonably efficient, but the length of the command
3917 line is limited not just by the operating system limits, but also by
3918 how many files we actually need to delete from each directory.
3920 Is it possible to do any better?   In the case of general file
3921 processing, no.  However, in the specific case of deleting files it is
3922 indeed possible to do better.  
3924 @subsection Using the -delete action
3926 The most efficient and secure method of solving this problem is to use
3927 the @samp{-delete} action:
3929 @smallexample
3930 find /var/tmp/stuff -mtime +90 -delete
3931 @end smallexample
3933 This alternative is more efficient than any of the @samp{-exec} or
3934 @samp{-execdir} actions, since it entirely avoids the overhead of
3935 forking a new process and using @code{exec} to run @code{/bin/rm}.  It
3936 is also normally more efficient than @code{xargs} for the same
3937 reason.   The file deletion is performed from the directory containing
3938 the entry to be deleted, so the @samp{-delete} action has the same
3939 security advantages as the @samp{-execdir} action has.  
3941 The @samp{-delete} action was introduced by the BSD family of
3942 operating systems.
3944 @subsection Improving things still further
3946 Is it possible to improve things still further?  Not without either
3947 modifying the system library to the operating system or having more specific
3948 knowledge of the layout of the filesystem and disk I/O subsystem, or
3949 both.
3951 The @code{find} command traverses the filesystem, reading
3952 directories.  It then issues a separate system call for each file to
3953 be deleted.  If we could modify the operating system, there are
3954 potential gains that could be made:
3956 @itemize
3957 @item
3958 We could have a system call to which we pass more than one filename
3959 for deletion
3960 @item
3961 Alternatively, we could pass in a list of inode numbers (on GNU/Linux
3962 systems, @code{readdir()} also returns the inode number of each
3963 directory entry) to be deleted.
3964 @end itemize
3966 The above possibilities sound interesting, but from the kernel's point
3967 of view it is difficult to enforce standard Unix access controls for
3968 such processing by inode number.  Such a facility would probably
3969 need to be restricted to the superuser.
3971 Another way of improving performance would be to increase the
3972 parallelism of the process.  For example if the directory hierarchy we
3973 are searching is actually spread across a number of disks, we might
3974 somehow be able to arrange for @code{find} to process each disk in
3975 parallel.  In practice GNU @code{find} doesn't have such an intimate
3976 understanding of the system's filesystem layout and disk I/O
3977 subsystem.
3979 However, since the system administrator can have such an understanding
3980 they can take advantage of it like so:
3982 @smallexample
3983 find /var/tmp/stuff1 -mtime +90 -delete &
3984 find /var/tmp/stuff2 -mtime +90 -delete &
3985 find /var/tmp/stuff3 -mtime +90 -delete &
3986 find /var/tmp/stuff4 -mtime +90 -delete &
3987 wait
3988 @end smallexample
3990 In the example above, four separate instances of @code{find} are used
3991 to search four subdirectories in parallel.  The @code{wait} command
3992 simply waits for all of these to complete.  Whether this approach is
3993 more or less efficient than a single instance of @code{find} depends
3994 on a number of things:
3996 @itemize
3997 @item
3998 Are the directories being searched in parallel actually on separate
3999 disks?  If not, this parallel search might just result in a lot of
4000 disk head movement and so the speed might even be slower.
4001 @item
4002 Other activity - are other programs also doing things on those disks?
4003 @end itemize
4006 @subsection Conclusion
4008 The fastest and most secure way to delete files with the help of
4009 @code{find} is to use @samp{-delete}.  Using @code{xargs -0 -P N} can
4010 also make effective use of the disk, but it is not as secure.
4012 In the case where we're doing things other than deleting files, the
4013 most secure alternative is @samp{-execdir @dots{} +}, but this is not as
4014 portable as the insecure action @samp{-exec @dots{} +}.
4016 The @samp{-delete} action is not completely portable, but the only
4017 other possibility which is as secure (@samp{-execdir}) is no more
4018 portable.  The most efficient portable alternative is @samp{-exec
4019 @dots{}+}, but this is insecure and isn't supported by versions of GNU
4020 findutils prior to 4.2.12.
4023 @node Updating A Timestamp File
4024 @section Updating A Timestamp File
4026 Suppose we have a directory full of files which is maintained with a
4027 set of automated tools; perhaps one set of tools updates them and
4028 another set of tools uses the result.  In this situation, it might be
4029 useful for the second set of tools to know if the files have recently
4030 been changed.  It might be useful, for example, to have a 'timestamp'
4031 file which gives the timestamp on the newest file in the collection.
4033 We can use @code{find} to achieve this, but there are several
4034 different ways to do it.
4036 @subsection Updating the Timestamp The Wrong Way
4038 The obvious but wrong answer is just to use @samp{-newer}:-
4040 @smallexample
4041 find subdir -newer timestamp -exec touch -r @{@} timestamp \; 
4042 @end smallexample
4044 This does the right sort of thing but has a bug.  Suppose that two
4045 files in the subdirectory have been updated, and that these are called
4046 @file{file1} and @file{file2}.  The command above will update
4047 @file{timestamp} with the modification time of @file{file1} or that of
4048 @file{file2}, but we don't know which one.  Since the timestamps on
4049 @file{file1} and @file{file2} will in general be different, this could
4050 well be the wrong value.
4052 One solution to this problem is to modify @code{find} to recheck the
4053 modification time of @file{timestamp} every time a file is to be
4054 compared against it, but that will reduce the performance of
4055 @code{find}.
4057 @subsection Using the test utility to compare timestamps
4059 The @code{test} command can be used to compare timestamps:
4061 @smallexample
4062 find subdir -exec test @{@} -nt timestamp \; -exec touch -r @{@} timestamp \; 
4063 @end smallexample
4065 This will ensure that any changes made to the modification time of
4066 @file{timestamp} that take place during the execution of @code{find}
4067 are taken into account.  This resolves our earlier problem, but
4068 unfortunately this runs much more slowly.
4070 @subsection A combined approach
4072 We can of course still use @samp{-newer} to cut down on the number of
4073 calls to @code{test}:
4075 @smallexample
4076 find subdir -newer timestamp -a \
4077      -exec test @{@} -nt timestamp \; -a \
4078      -exec touch -r @{@} timestamp \; 
4079 @end smallexample
4081 Here, the @samp{-newer} test excludes all the files which are
4082 definitely older than the timestamp, but all the files which are newer
4083 than the old value of the timestamp are compared against the current
4084 updated timestamp.
4086 This is indeed faster in general, but the speed difference will depend
4087 on how many updated files there are.
4089 @subsection Using -printf and sort to compare timestamps
4091 It is possible to use the @samp{-printf} action to abandon the use of
4092 @code{test} entirely:
4094 @smallexample
4095 newest=$(find subdir -newer timestamp -printf "%A@:%p\n" | 
4096            sort -n | 
4097            tail -1 | 
4098            cut -d: -f2- ) 
4099 touch -r "$@{newest:-timestamp@}" timestamp
4100 @end smallexample
4102 The command above works by generating a list of the timestamps and
4103 names of all the files which are newer than the timestamp.  The
4104 @code{sort}, @code{tail} and @code{cut} commands simply pull out the
4105 name of the file with the largest timestamp value (that is, the latest
4106 file).  The @code{touch} command is then used to update the timestamp,
4108 The @code{"$@{newest:-timestamp@}"} expression simply expands to the
4109 value of @code{$newest} if that variable is set, but to
4110 @file{timestamp} otherwise.  This ensures that an argument is always
4111 given to the @samp{-r} option of the @code{touch} command.
4113 This approach seems quite efficient, but unfortunately it has a bug.
4114 Many operating systems now keep file modification time information at
4115 a granularity which is finer than one second.  Unfortunately the
4116 @samp{%A@@} format for @samp{-printf} only prints a whole-number value
4117 currently; that is, these values are at a one-second granularity.
4118 This means that in our example above, @samp{$newest} will be the name
4119 of a file which is no more than one second older than the newest file,
4120 but may indeed be older.
4122 It would be possible to solve this problem with some kind of loop:
4124 @smallexample
4125 while true; do
4126         newest=$(find subdir -newer timestamp -printf "%A@@:%p\n" | 
4127            sort -n | 
4128            tail -1 | 
4129            cut -d: -f2- ) 
4130         if test -z "$newest" ; then
4131                 break
4132         else
4133                 touch -r "$newest" timestamp
4134         fi
4135 done
4136 @end smallexample
4138 A better fix for this problem would be to allow the @samp{%A@@} format
4139 to produce a result having a fractional part, too.  While this is
4140 planned for GNU @code{find}, it hasn't been done yet.
4142 @subsection Coping with sub-second timestamp resolution
4144 Another tool which often works with timestamps is @code{make}.  We can
4145 use @code{find} to generate a @file{Makefile} file on the fly and then
4146 use @code{make} to update the timestamps:
4148 @smallexample
4149 makefile=$(mktemp)
4150 find subdir \
4151         \( \! -xtype l \) \
4152         -newer timestamp \
4153         -printf "timestamp:: %p\n\ttouch -r %p timestamp\n\n" > "$makefile"
4154 make -f "$makefile"
4155 rm   -f "$makefile"
4156 @end smallexample
4158 Unfortunately although the solution above is quite elegant, it fails
4159 to cope with white space within file names, and adjusting it to do so
4160 would require a rather complex shell script.
4163 @subsection Coping with odd filenames too
4165 We can fix both of these problems (looping and problems with white
4166 space), and do things more efficiently too.  The following command
4167 works with newlines and doesn't need to sort the list of filenames.
4169 @smallexample
4170 find subdir -newer timestamp -printf "%A@@:%p\0" | 
4171    perl -0 newest.pl |
4172    xargs --no-run-if-empty --null -i \
4173       find @{@} -maxdepth 0 -newer timestamp -exec touch -r @{@} timestamp \;
4174 @end smallexample
4176 The first @code{find} command generates a list of files which are
4177 newer than the original timestamp file, and prints a list of them with
4178 their timestamps.  The @file{newest.pl} script simply filters out all
4179 the filenames which have timestamps which are older than whatever the
4180 newest file is:-
4182 @smallexample
4183 @verbatim
4184 #! /usr/bin/perl -0
4185 my @newest = ();
4186 my $latest_stamp = undef;
4187 while (<>) {
4188     my ($stamp, $name) = split(/:/);
4189     if (!defined($latest_stamp) || ($tstamp > $latest_stamp)) {
4190         $latest_stamp = $stamp;
4191         @newest = ();
4192     }
4193     if ($tstamp >= $latest_stamp) {
4194         push @newest, $name;
4195     }
4197 print join("\0", @newest);
4198 @end verbatim
4199 @end smallexample
4201 This prints a list of zero or more files, all of which are newer than
4202 the original timestamp file, and which have the same timestamp as each
4203 other, to the nearest second.  The second @code{find} command takes
4204 each resulting file one at a time, and if that is newer than the
4205 timestamp file, the timestamp is updated.
4207 @node Security Considerations
4208 @chapter Security Considerations
4210 Security considerations are important if you are using @code{find} or
4211 @code{xargs} to search for or process files that don't belong to you
4212 or which other people have control.  Security considerations
4213 relating to @code{locate} may also apply if you have files which you
4214 do not want others to see.
4216 The most severe forms of security problems affecting
4217 @code{find} and related programs are when third parties bring
4218 about a situation allowing them to do something
4219 they would normally not be able to accomplish.  This is called @emph{privilege
4220 elevation}.  This might include deleting files they would not normally
4221 be able to delete.  It is common for the operating system to periodically
4222 invoke @code{find} for self-maintenance purposes.  These invocations of
4223 @code{find} are particularly problematic from a security point of view
4224 as these are often invoked by the superuser and search the entire
4225 filesystem hierarchy.  Generally, the severity of any associated problem depends
4226 on what the system is going to do with the files found by @code{find}.
4228 @menu
4229 * Levels of Risk::      What is your level of exposure to security problems?
4230 * Security Considerations for find::  Security problems with find
4231 * Security Considerations for xargs:: Security problems with xargs
4232 * Security Considerations for locate:: Security problems with locate
4233 * Security Summary:: That was all very complex, what does it boil down to?
4234 @end menu
4237 @node Levels of Risk
4238 @section Levels of Risk
4240 There are some security risks inherent in the use of @code{find},
4241 @code{xargs} and (to a lesser extent) @code{locate}.  The severity of
4242 these risks depends on what sort of system you are using:
4244 @table @strong
4245 @item High risk
4246 Multi-user systems where you do not control (or trust) the other
4247 users, and on which you execute @code{find}, including areas where
4248 those other users can manipulate the filesystem (for example beneath
4249 @file{/home} or @file{/tmp}).
4251 @item Medium Risk
4252 Systems where the actions of other users can create file names chosen
4253 by them, but to which they don't have access while @code{find} is
4254 being run.  This access might include leaving programs running (shell
4255 background jobs, @code{at} or @code{cron} tasks, for example).  On
4256 these sorts of systems, carefully written commands (avoiding use of
4257 @samp{-print} for example) should not expose you to a high degree of
4258 risk.  Most systems fall into this category.
4260 @item Low Risk
4261 Systems to which untrusted parties do not have access, cannot create
4262 file names of their own choice (even remotely) and which contain no
4263 security flaws which might enable an untrusted third party to gain
4264 access.  Most systems do not fall into this category because there are
4265 many ways in which external parties can affect the names of files that
4266 are created on your system.  The system on which I am writing this for
4267 example automatically downloads software updates from the Internet;
4268 the names of the files in which these updates exist are chosen by
4269 third parties@footnote{Of course, I trust these parties to a large
4270 extent anyway, because I install software provided by them; I choose
4271 to trust them in this way, and that's a deliberate choice}.
4272 @end table
4274 In the discussion above, ``risk'' denotes the likelihood that someone
4275 can cause @code{find}, @code{xargs}, @code{locate} or some other
4276 program which is controlled by them to do something you did not
4277 intend.  The levels of risk suggested do not take any account of the
4278 consequences of this sort of event.  That is, if you operate a ``low
4279 risk'' type system, but the consequences of a security problem are
4280 disastrous, then you should still give serious thought to all the
4281 possible security problems, many of which of course will not be
4282 discussed here -- this section of the manual is intended to be
4283 informative but not comprehensive or exhaustive.
4285 If you are responsible for the operation of a system where the
4286 consequences of a security problem could be very important, you should
4287 do two things:-
4289 @enumerate
4290 @item Define a security policy which defines who is allowed to do what
4291 on your system.
4292 @item Seek competent advice on how to enforce your policy, detect
4293 breaches of that policy, and take account of any potential problems
4294 that might fall outside the scope of your policy.
4295 @end enumerate
4298 @node Security Considerations for find
4299 @section Security Considerations for @code{find}
4302 Some of the actions @code{find} might take have a direct effect;
4303 these include @code{-exec} and @code{-delete}.  However, it is also
4304 common to use @code{-print} explicitly or implicitly, and so if
4305 @code{find} produces the wrong list of file names, that can also be a
4306 security problem; consider the case for example where @code{find} is
4307 producing a list of files to be deleted.
4309 We normally assume that the @code{find} command line expresses the
4310 file selection criteria and actions that the user had in mind -- that
4311 is, the command line is ``trusted'' data.
4313 From a security analysis point of view, the output of @code{find}
4314 should be correct; that is, the output should contain only the names
4315 of those files which meet the user's criteria specified on the command
4316 line.  This applies for the @code{-exec} and @code{-delete} actions;
4317 one can consider these to be part of the output.
4319 On the other hand, the contents of the filesystem can be manipulated
4320 by other people, and hence we regard this as ``untrusted'' data.  This
4321 implies that the @code{find} command line is a filter which converts
4322 the untrusted contents of the filesystem into a correct list of output
4323 files.
4325 The filesystem will in general change while @code{find} is searching
4326 it; in fact, most of the potential security problems with @code{find}
4327 relate to this issue in some way.
4329 @dfn{Race conditions} are a general class of security problem where the
4330 relative ordering of actions taken by @code{find} (for example) and
4331 something else are critically important in getting the correct and expected result@footnote{This is more or less the
4332 definition of the term ``race condition''} .
4334 For @code{find}, an attacker might move or rename files or directories in
4335 the hope that an action might be taken against a file which was not
4336 normally intended to be affected.  Alternatively, this sort of attack
4337 might be intended to persuade @code{find} to search part of the
4338 filesystem which would not normally be included in the search
4339 (defeating the @code{-prune} action for example).
4341 @menu
4342 * Problems with -exec and filenames::
4343 * Changing the Current Working Directory::
4344 * Race Conditions with -exec::
4345 * Race Conditions with -print and -print0::
4346 @end menu
4348 @node Problems with -exec and filenames
4349 @subsection Problems with -exec and filenames
4351 It is safe in many cases to use the @samp{-execdir} action with any
4352 file name.  Because @samp{-execdir} prefixes the arguments it passes
4353 to programs with @samp{./}, you will not accidentally pass an argument
4354 which is interpreted as an option.  For example the file @file{-f}
4355 would be passed to @code{rm} as @file{./-f}, which is harmless.
4357 However, your degree of safety does depend on the nature of the
4358 program you are running.  For example constructs such as these two commands
4360 @example
4361 # risky
4362 find -exec sh -c "something @{@}" \;
4363 find -execdir sh -c "something @{@}" \;
4364 @end example
4366 are very dangerous.  The reason for this is that the @samp{@{@}} is
4367 expanded to a filename which might contain a semicolon or other
4368 characters special to the shell.  If for example someone creates the
4369 file @file{/tmp/foo; rm -rf $HOME} then the two commands above could
4370 delete someone's home directory.
4372 So for this reason do not run any command which will pass untrusted
4373 data (such as the names of files) to commands which interpret
4374 arguments as commands to be further interpreted (for example
4375 @samp{sh}).
4377 In the case of the shell, there is a clever workaround for this
4378 problem:
4380 @example
4381 # safer 
4382 find -exec sh -c 'something "$@@"' @{@} \;
4383 find -execdir sh -c 'something "$@@"' @{@}\;
4384 @end example
4386 This approach is not guaranteed to avoid every problem, but it is much
4387 safer than substituting data of an attacker's choice into the text of
4388 a shell command.
4390 @node Changing the Current Working Directory
4391 @subsection Changing the Current Working Directory
4393 As @code{find} searches the filesystem, it finds subdirectories and
4394 then searches within them by changing its working directory.  First,
4395 @code{find} reaches and recognises a subdirectory.  It then decides if that
4396 subdirectory meets the criteria for being searched; that is, any
4397 @samp{-xdev} or @samp{-prune} expressions are taken into account.  The
4398 @code{find} program will then change working directory and proceed to
4399 search the directory.
4401 A race condition attack might take the form that once the checks
4402 relevant to @samp{-xdev} and @samp{-prune} have been done, an attacker
4403 might rename the directory that was being considered, and put in its
4404 place a symbolic link that actually points somewhere else.
4406 The idea behind this attack is to fool @code{find} into going into the
4407 wrong directory.  This would leave @code{find} with a working
4408 directory chosen by an attacker, bypassing any protection apparently
4409 provided by @samp{-xdev} and @samp{-prune}, and any protection
4410 provided by being able to @emph{not} list particular directories on
4411 the @code{find} command line.  This form of attack is particularly
4412 problematic if the attacker can predict when the @code{find} command
4413 will be run, as is the case with @code{cron} tasks for example.
4415 GNU @code{find} has specific safeguards to prevent this general class
4416 of problem.  The exact form of these safeguards depends on the
4417 properties of your system.
4419 @menu
4420 * O_NOFOLLOW::                     Safely changing directory using fchdir().
4421 * Systems without O_NOFOLLOW::     Checking for symbolic links after chdir().
4422 @end menu
4424 @node O_NOFOLLOW
4425 @subsubsection O_NOFOLLOW
4427 If your system supports the O_NOFOLLOW flag @footnote{GNU/Linux
4428 (kernel version 2.1.126 and later) and FreeBSD (3.0-CURRENT and later)
4429 support this} to the @code{open(2)} system call, @code{find} uses it
4430 when safely changing directory.  The target directory is first opened
4431 and then @code{find} changes working directory with the
4432 @code{fchdir()} system call.  This ensures that symbolic links are not
4433 followed, preventing the sort of race condition attack in which use
4434 is made of symbolic links.
4436 If for any reason this approach does not work, @code{find} will fall
4437 back on the method which is normally used if O_NOFOLLOW is not
4438 supported.
4440 You can tell if your system supports O_NOFOLLOW by running
4442 @example
4443 find --version
4444 @end example
4446 This will tell you the version number and which features are enabled.
4447 For example, if I run this on my system now, this gives:
4448 @example
4449 GNU find version 4.2.18-CVS
4450 Features enabled: D_TYPE O_NOFOLLOW(enabled)
4451 @end example
4453 Here, you can see that I am running a version of @code{find} which was
4454 built from the development (CVS) code prior to the release of
4455 findutils-4.2.18, and that the D_TYPE and O_NOFOLLOW features are
4456 present.  O_NOFOLLOW is qualified with ``enabled''.  This simply means
4457 that the current system seems to support O_NOFOLLOW.  This check is
4458 needed because it is possible to build @code{find} on a system that
4459 defines O_NOFOLLOW and then run it on a system that ignores the
4460 O_NOFOLLOW flag.  We try to detect such cases at startup by checking
4461 the operating system and version number; when this happens you will
4462 see ``O_NOFOLLOW(disabled)'' instead.
4464 @node Systems without O_NOFOLLOW
4465 @subsubsection Systems without O_NOFOLLOW
4467 The strategy for preventing this type of problem on systems that lack
4468 support for the O_NOFOLLOW flag is more complex.  Each time
4469 @code{find} changes directory, it examines the directory it is about
4470 to move to, issues the @code{chdir()} system call, and then checks
4471 that it has ended up in the subdirectory it expected.  If all is as
4472 expected, processing continues as normal.  However, there are two main
4473 reasons why the directory might change: the use of an automounter and
4474 the someone removing the old directory and replacing it with something
4475 else while @code{find} is trying to descend into it.
4477 Where a filesystem ``automounter'' is in use it can be the case that
4478 the use of the @code{chdir()} system call can itself cause a new
4479 filesystem to be mounted at that point.  On systems that do not
4480 support O_NOFOLLOW, this will cause @code{find}'s security check to
4481 fail.
4483 However, this does not normally represent a security problem, since
4484 the automounter configuration is normally set up by the system
4485 administrator.  Therefore, if the @code{chdir()} sanity check fails,
4486 @code{find} will make one more attempt@footnote{This may not be the
4487 case for the fts-based executable}.  If that succeeds, execution
4488 carries on as normal.  This is the usual case for automounters.
4490 Where an attacker is trying to exploit a race condition, the problem
4491 may not have gone away on the second attempt.  If this is the case,
4492 @code{find} will issue a warning message and then ignore that
4493 subdirectory.  When this happens, actions such as @samp{-exec} or
4494 @samp{-print} may already have taken place for the problematic
4495 subdirectory.  This is because @code{find} applies tests and actions
4496 to directories before searching within them (unless @samp{-depth} was
4497 specified).
4499 Because of the nature of the directory-change operation and security
4500 check, in the worst case the only things that @code{find} would have
4501 done with the directory are to move into it and back out to the
4502 original parent.  No operations would have been performed within that
4503 directory.
4505 @node Race Conditions with -exec
4506 @subsection Race Conditions with -exec
4508 The @samp{-exec} action causes another program to be run.  It passes
4509 to the program the name of the file which is being considered at the
4510 time.  The invoked program will typically then perform some action
4511 on that file.  Once again, there is a race condition which can be
4512 exploited here.  We shall take as a specific example the command
4514 @example
4515 find /tmp -path /tmp/umsp/passwd -exec /bin/rm
4516 @end example
4518 In this simple example, we are identifying just one file to be deleted
4519 and invoking @code{/bin/rm} to delete it.  A problem exists because
4520 there is a time gap between the point where @code{find} decides that
4521 it needs to process the @samp{-exec} action and the point where the
4522 @code{/bin/rm} command actually issues the @code{unlink()} system
4523 call to delete the file from the filesystem.  Within this time period, an attacker can rename the
4524 @file{/tmp/umsp} directory, replacing it with a symbolic link to
4525 @file{/etc}.  There is no way for @code{/bin/rm} to determine that it
4526 is working on the same file that @code{find} had in mind.  Once the
4527 symbolic link is in place, the attacker has persuaded @code{find} to
4528 cause the deletion of the @file{/etc/passwd} file, which is not the
4529 effect intended by the command which was actually invoked.
4531 One possible defence against this type of attack is to modify the
4532 behaviour of @samp{-exec} so that the @code{/bin/rm} command is run
4533 with the argument @file{./passwd} and a suitable choice of working
4534 directory.  This would allow the normal sanity check that @code{find}
4535 performs to protect against this form of attack too.  Unfortunately,
4536 this strategy cannot be used as the POSIX standard specifies that the
4537 current working directory for commands invoked with @samp{-exec} must
4538 be the same as the current working directory from which @code{find}
4539 was invoked.  This means that the @samp{-exec} action is inherently
4540 insecure and can't be fixed.
4542 GNU @code{find} implements a more secure variant of the @samp{-exec}
4543 action, @samp{-execdir}.  The @samp{-execdir} action
4544 ensures that it is not necessary to dereference subdirectories to
4545 process target files.  The current directory used to invoke programs
4546 is the same as the directory in which the file to be processed exists
4547 (@file{/tmp/umsp} in our example, and only the basename of the file to
4548 be processed is passed to the invoked command, with a @samp{./}
4549 prepended (giving @file{./passwd} in our example).
4551 The @samp{-execdir} action refuses to do anything if the current
4552 directory is included in the @var{$PATH} environment variable.  This
4553 is necessary because @samp{-execdir} runs programs in the same
4554 directory in which it finds files -- in general, such a directory
4555 might be writable by untrusted users.  For similar reasons,
4556 @samp{-execdir} does not allow @samp{@{@}} to appear in the name of
4557 the command to be run.
4559 @node Race Conditions with -print and -print0
4560 @subsection Race Conditions with -print and -print0
4562 The @samp{-print} and @samp{-print0} actions can be used to produce a
4563 list of files matching some criteria, which can then be used with some
4564 other command, perhaps with @code{xargs}.  Unfortunately, this means
4565 that there is an unavoidable time gap between @code{find} deciding
4566 that one or more files meet its criteria and the relevant command
4567 being executed.  For this reason, the @samp{-print} and @samp{-print0}
4568 actions are just as insecure as @samp{-exec}.
4570 In fact, since the construction
4572 @example
4573 find @dots{}  -print | xargs @enddots{}
4574 @end example
4576 does not cope correctly with newlines or other ``white space'' in
4577 file names, and copes poorly with file names containing quotes, the
4578 @samp{-print} action is less secure even than @samp{-print0}.
4581 @comment  node-name,  next,  previous,  up
4582 @comment @node Security Considerations for xargs
4583 @node Security Considerations for xargs
4584 @section Security Considerations for @code{xargs}
4586 The description of the race conditions affecting the @samp{-print}
4587 action of @code{find} shows that @code{xargs} cannot be secure if it
4588 is possible for an attacker to modify a filesystem after @code{find}
4589 has started but before @code{xargs} has completed all its actions.
4591 However, there are other security issues that exist even if it is not
4592 possible for an attacker to have access to the filesystem in real
4593 time.  Firstly, if it is possible for an attacker to create files with
4594 names of their choice on the filesystem, then @code{xargs} is
4595 insecure unless the @samp{-0} option is used.  If a file with the name
4596 @file{/home/someuser/foo/bar\n/etc/passwd} exists (assume that
4597 @samp{\n} stands for a newline character), then @code{find @dots{} -print}
4598 can be persuaded to print three separate lines:
4600 @example
4601 /home/someuser/foo/bar
4603 /etc/passwd
4604 @end example
4606 If it finds a blank line in the input, @code{xargs} will ignore it.
4607 Therefore, if some action is to be taken on the basis of this list of
4608 files, the @file{/etc/passwd} file would be included even if this was
4609 not the intent of the person running find.  There are circumstances in
4610 which an attacker can use this to their advantage.  The same
4611 consideration applies to file names containing ordinary spaces rather
4612 than newlines, except that of course the list of file names will no
4613 longer contain an ``extra'' newline.
4615 This problem is an unavoidable consequence of the default behaviour of
4616 the @code{xargs} command, which is specified by the POSIX standard.
4617 The only ways to avoid this problem are either to avoid all use of
4618 @code{xargs} in favour for example of @samp{find -exec} or (where
4619 available) @samp{find -execdir}, or to use the @samp{-0} option, which
4620 ensures that @code{xargs} considers file names to be separated by
4621 ASCII NUL characters rather than whitespace.  However, useful as this
4622 option is, the POSIX standard does not make it mandatory.
4624 POSIX also specifies that @code{xargs} interprets quoting and trailing
4625 whitespace specially in filenames, too.  This means that using
4626 @code{find ... -print | xargs ...} can cause the commands run by
4627 @code{xargs} to receive a list of file names which is not the same as
4628 the list printed by @code{find}.   The interpretation of quotes and
4629 trailing whitespace is turned off by the @samp{-0} argument to
4630 @code{xargs}, which is another reason to use that option.
4632 @comment  node-name,  next,  previous,  up
4633 @node Security Considerations for locate
4634 @section Security Considerations for @code{locate}
4636 It is fairly unusual for the output of @code{locate} to be fed into
4637 another command.  However, if this were to be done, this would raise
4638 the same set of security issues as the use of @samp{find @dots{} -print}.
4639 Although the problems relating to whitespace in file names can be
4640 resolved by using @code{locate}'s @samp{-0} option, this still leaves
4641 the race condition problems associated with @samp{find @dots{} -print0}.
4642 There is no way to avoid these problems in the case of @code{locate}.
4644 @node Security Summary
4645 @section Summary
4647 Where untrusted parties can create files on the system, or affect the
4648 names of files that are created, all uses for @code{find},
4649 @code{locate} and @code{xargs} have known security problems except the
4650 following:
4652 @table @asis
4653 @item Informational use only
4654 Uses where the programs are used to prepare lists of file names upon
4655 which no further action will ever be taken.
4657 @item @samp{-delete}
4658 Use of the @samp{-delete} action with @code{find} to delete files
4659 which meet specified criteria
4661 @item @samp{-execdir}
4662 Use of the @samp{-execdir} action with @code{find} where the
4663 @env{PATH} environment variable contains directories which contain
4664 only trusted programs.
4665 @end table
4667 @comment  node-name,  next,  previous,  up
4668 @node Error Messages
4669 @chapter Error Messages
4671 This section describes some of the error messages sometimes made by
4672 @code{find}, @code{xargs}, or @code{locate}, explains them and in some
4673 cases provides advice as to what you should do about this.
4675 This manual is written in English.  The GNU findutils software
4676 features translations of error messages for many languages.  For this
4677 reason the error messages produced by the programs are made to be as
4678 self-explanatory as possible.  This approach avoids leaving people to
4679 figure out which test an English-language error message corresponds
4680 to.  Error messages which are self-explanatory will not normally be
4681 mentioned in this document.  For those messages mentioned in this
4682 document, only the English-language version of the message will be
4683 listed.
4685 @menu
4686 * Error Messages From find::
4687 * Error Messages From xargs::
4688 * Error Messages From locate::
4689 * Error Messages From updatedb::
4690 @end menu
4692 @node Error Messages From find
4693 @section Error Messages From @code{find}
4695 @table @samp
4696 @item invalid predicate `-foo'
4697 This means that the @code{find} command line included something that
4698 started with a dash or other special character.  The @code{find}
4699 program tried to interpret this as a test, action or option, but
4700 didn't recognise it.  If it was intended to be a test, check what was
4701 specified against the documentation.  If, on the other hand, the
4702 string is the name of a file which has been expanded from a wildcard
4703 (for example because you have a @samp{*} on the command line),
4704 consider using @samp{./*} or just @samp{.} instead.
4706 @item unexpected extra predicate
4707 This usually happens if you have an extra bracket on the command line
4708 (for example @samp{find . -print \)}).
4710 @item Warning: filesystem /path/foo has recently been mounted
4711 @itemx Warning: filesystem /path/foo has recently been unmounted
4712 These messages might appear when @code{find} moves into a directory
4713 and finds that the device number and inode are different to what it
4714 expected them to be.  If the directory @code{find} has moved into is
4715 on an network filesystem (NFS), it will not issue this message, because
4716 @code{automount} frequently mounts new filesystems on directories as
4717 you move into them (that is how it knows you want to use the
4718 filesystem).  So, if you do see this message, be wary ---
4719 @code{automount} may not have been responsible.  Consider the
4720 possibility that someone else is manipulating the filesystem while
4721 @code{find} is running.  Some people might do this in order to mislead
4722 @code{find} or persuade it to look at one set of files when it thought
4723 it was looking at another set.
4725 @item /path/foo changed during execution of find (old device number 12345, new device number 6789, filesystem type is <whatever>) [ref XXX]
4726 This message is issued when @code{find} moves into a directory and ends up
4727 somewhere it didn't expect to be.  This happens in one of two
4728 circumstances.  Firstly, this happens when @code{automount} intervenes
4729 on a system where @code{find} doesn't know how to determine what
4730 the current set of mounted filesystems is.
4732 Secondly, this can happen when the device number of a directory
4733 appears to change during a change of current directory, but
4734 @code{find} is moving up the filesystem hierarchy rather than down into it.
4735 In order to prevent @code{find} wandering off into some unexpected
4736 part of the filesystem, we stop it at this point.
4738 @item Don't know how to use getmntent() to read `/etc/mtab'.  This is a bug.
4739 This message is issued when a problem similar to the above occurs on a
4740 system where @code{find} doesn't know how to figure out the current
4741 list of mount points.  Ask for help on @email{bug-findutils@@gnu.org}.
4743 @item /path/foo/bar changed during execution of find (old inode number 12345, new inode number 67893, filesystem type is <whatever>) [ref XXX]"),
4744 This message is issued when @code{find} moves into a directory and
4745 discovers that the inode number of that directory
4746 is different from the inode number that it obtained when it examined the
4747 directory previously.  This usually means that while
4748 @code{find} was deep in a directory hierarchy doing a
4749 time consuming operation, somebody has moved one of the parent directories to
4750 another location in the same filesystem.  This may or may not have been done
4751 maliciously.  In any case, @code{find} stops at this point
4752 to avoid traversing parts of the filesystem that it wasn't
4753 intended.  You can use @code{ls -li} or @code{find /path -inum
4754 12345 -o -inum 67893} to find out more about what has happened.
4756 @item sanity check of the fnmatch() library function failed.
4757 Please submit a bug report.  You may well be asked questions about
4758 your system, and if you compiled the @code{findutils} code yourself,
4759 you should keep your copy of the build tree around.  The likely
4760 explanation is that your system has a buggy implementation of
4761 @code{fnmatch} that looks enough like the GNU version to fool
4762 @code{configure}, but which doesn't work properly.
4764 @item cannot fork
4765 This normally happens if you use the @code{-exec} action or
4766 something similar (@code{-ok} and so forth) but the system has run out
4767 of free process slots.  This is either because the system is very busy
4768 and the system has reached its maximum process limit, or because you
4769 have a resource limit in place and you've reached it.  Check the
4770 system for runaway processes (with @code{ps}, if possible).  Some process
4771 slots are normally reserved for use by @samp{root}.
4773 @item some-program terminated by signal 99
4774 Some program which was launched with @code{-exec} or similar was killed
4775 with a fatal signal.  This is just an advisory message.
4776 @end table
4779 @node Error Messages From xargs
4780 @section Error Messages From xargs
4782 @table @samp
4783 @item environment is too large for exec
4784 This message means that you have so many environment variables set (or
4785 such large values for them) that there is no room within the
4786 system-imposed limits on program command line argument length to
4787 invoke any program.  This is an unlikely situation and is more likely
4788 result of an attempt to test the limits of @code{xargs}, or break it.
4789 Please try unsetting some environment variables, or exiting the
4790 current shell.  You can also use @samp{xargs --show-limits} to
4791 understand the relevant sizes.
4793 @item can not fit single argument within argument list size limit
4794 You are using the @samp{-I} option and @code{xargs} doesn't have
4795 enough space to build a command line because it has read a really
4796 large item and it doesn't fit.  You can probably work around this
4797 problem with the @samp{-s} option, but the default size is pretty
4798 large.  This is a rare situation and is more likely an attempt to test
4799 the limits of @code{xargs}, or break it.  Otherwise, you will need to
4800 try to shorten the problematic argument or not use @code{xargs}.
4802 @item cannot fork
4803 See the description of the similar message for @code{find}.
4805 @item <program>: exited with status 255; aborting
4806 When a command run by @code{xargs} exits with status 255, @code{xargs}
4807 is supposed to stop.  If this is not what you intended, wrap the
4808 program you are trying to invoke in a shell script which doesn't
4809 return status 255.
4811 @item <program>: terminated by signal 99
4812 See the description of the similar message for @code{find}.
4813 @end table
4815 @node Error Messages From locate
4816 @section Error Messages From @code{locate}
4818 @table @samp
4819 @item warning: database `/usr/local/var/locatedb' is more than 8 days old
4820 The @code{locate} program relies on a database which is periodically
4821 built by the @code{updatedb} program.  That hasn't happened in a long
4822 time.  To fix this problem, run @code{updatedb} manually.  This can
4823 often happen on systems that are generally not left on, so the
4824 periodic ``cron'' task which normally does this doesn't get a chance
4825 to run.
4827 @item locate database `/usr/local/var/locatedb' is corrupt or invalid
4828 This should not happen.  Re-run @code{updatedb}.  If that works, but
4829 @code{locate} still produces this error, run @code{locate --version}
4830 and @code{updatedb --version}.  These should produce the same output.
4831 If not, you are using a mixed toolset; check your @samp{$PATH}
4832 environment variable and your shell aliases (if you have any).  If
4833 both programs claim to be GNU versions, this is a bug; all versions of
4834 these programs should interoperate without problem.  Ask for help on
4835 @email{bug-findutils@@gnu.org}.
4836 @end table
4839 @node Error Messages From updatedb
4840 @section Error Messages From updatedb
4842 The @code{updatedb} program (and the programs it invokes) do issue
4843 error messages, but none seem to be candidates for guidance.  If
4844 you are having a problem understanding one of these, ask for help on
4845 @email{bug-findutils@@gnu.org}.
4848 @node Primary Index
4849 @unnumbered @code{find} Primary Index
4851 This is a list of all of the primaries (tests, actions, and options)
4852 that make up @code{find} expressions for selecting files.  @xref{find
4853 Expressions}, for more information on expressions.
4855 @printindex fn
4857 @bye
4859 @comment texi related words used by Emacs' spell checker ispell.el
4861 @comment LocalWords: texinfo setfilename settitle setchapternewpage
4862 @comment LocalWords: iftex finalout ifinfo DIR titlepage vskip pt
4863 @comment LocalWords: filll dir samp dfn noindent xref pxref
4864 @comment LocalWords: var deffn texi deffnx itemx emph asis
4865 @comment LocalWords: findex smallexample subsubsection cindex
4866 @comment LocalWords: dircategory direntry itemize
4868 @comment other words used by Emacs' spell checker ispell.el
4869 @comment LocalWords: README fred updatedb xargs Plett Rendell akefile
4870 @comment LocalWords: args grep Filesystems fo foo fOo wildcards iname
4871 @comment LocalWords: ipath regex iregex expr fubar regexps
4872 @comment LocalWords: metacharacters macs sr sc inode lname ilname
4873 @comment LocalWords: sysdep noleaf ls inum xdev filesystems usr atime
4874 @comment LocalWords: ctime mtime amin cmin mmin al daystart Sladkey rm
4875 @comment LocalWords: anewer cnewer bckw rf xtype uname gname uid gid
4876 @comment LocalWords: nouser nogroup chown chgrp perm ch maxdepth
4877 @comment LocalWords: mindepth cpio src CD AFS statted stat fstype ufs
4878 @comment LocalWords: nfs tmp mfs printf fprint dils rw djm Nov lwall
4879 @comment LocalWords: POSIXLY fls fprintf strftime locale's EDT GMT AP
4880 @comment LocalWords: EST diff perl backquotes sprintf Falstad Oct cron
4881 @comment LocalWords: eg vmunix mkdir afs allexec allwrite ARG bigram
4882 @comment LocalWords: bigrams cd chmod comp crc CVS dbfile dum eof
4883 @comment LocalWords: fileserver filesystem fn frcode Ghazi Hnewc iXX
4884 @comment LocalWords: joeuser Kaveh localpaths localuser LOGNAME
4885 @comment LocalWords: Meyering mv netpaths netuser nonblank nonblanks
4886 @comment LocalWords: ois ok Pinard printindex proc procs prunefs
4887 @comment LocalWords: prunepaths pwd RFS rmadillo rmdir rsh sbins str
4888 @comment LocalWords: su Timar ubins ug unstripped vf VM Weitzel
4889 @comment LocalWords: wildcard zlogout basename execdir wholename iwholename
4890 @comment LocalWords: timestamp timestamps Solaris FreeBSD OpenBSD POSIX