Updated Catalan translation from Translation Project
[findutils.git] / doc / find.texi
blob575847622547ffcacde0efe8b7e5e79591d7c595
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
64 @page
65 @vskip 0pt plus 1filll
66 @insertcopying{}
67 @end titlepage
69 @contents
71 @ifnottex
72 @node Top, Introduction, , (dir)
73 @comment  node-name,  next,  previous,  up
75 This file documents the GNU utilities for finding files that match
76 certain criteria and performing various actions on them.
78 This is edition @value{EDITION}, for @code{find} version @value{VERSION}.
79 @end ifnottex
81 @c The master menu, created with texinfo-master-menu, goes here.
83 @menu
84 * Introduction::                Summary of the tasks this manual describes.
85 * Finding Files::               Finding files that match certain criteria.
86 * Actions::                     Doing things to files you have found.
87 * Databases::                   Maintaining file name databases.
88 * File Permissions::            How to control access to files.
89 * Reference::                   Summary of how to invoke the programs.
90 * Common Tasks::                Solutions to common real-world problems.
91 * Worked Examples::             Examples demonstrating more complex points.
92 * Security Considerations::     Security issues relating to findutils.
93 * Error Messages::              Explanations of some messages you might see.
94 * Primary Index::               The components of @code{find} expressions.
95 @end menu
97 @node Introduction, Finding Files, Top, Top
98 @chapter Introduction
100 This manual shows how to find files that meet criteria you specify,
101 and how to perform various actions on the files that you find.  The
102 principal programs that you use to perform these tasks are
103 @code{find}, @code{locate}, and @code{xargs}.  Some of the examples in
104 this manual use capabilities specific to the GNU versions of those
105 programs.
107 GNU @code{find} was originally written by Eric Decker, with
108 enhancements by David MacKenzie, Jay Plett, and Tim Wood.  GNU
109 @code{xargs} was originally written by Mike Rendell, with enhancements
110 by David MacKenzie.  GNU @code{locate} and its associated utilities
111 were originally written by James Woods, with enhancements by David
112 MacKenzie.  The idea for @samp{find -print0} and @samp{xargs -0} came
113 from Dan Bernstein.  The current maintainer of GNU findutils (and this
114 manual) is James Youngman.  Many other people have contributed bug
115 fixes, small improvements, and helpful suggestions.  Thanks!
117 Mail suggestions and bug reports for these programs to
118 @code{bug-findutils@@gnu.org}.  Please include the version
119 number, which you can get by running @samp{find --version}.
121 @menu
122 * Scope::
123 * Overview::
124 * find Expressions::
125 @end menu
127 @node Scope
128 @section Scope
130 For brevity, the word @dfn{file} in this manual means a regular file,
131 a directory, a symbolic link, or any other kind of node that has a
132 directory entry.  A directory entry is also called a @dfn{file name}.
133 A file name may contain some, all, or none of the directories in a
134 path that leads to the file.  These are all examples of what this
135 manual calls ``file names'':
137 @example
138 parser.c
139 README
140 ./budget/may-94.sc
141 fred/.cshrc
142 /usr/local/include/termcap.h
143 @end example
145 A @dfn{directory tree} is a directory and the files it contains, all
146 of its subdirectories and the files they contain, etc.  It can also be
147 a single non-directory file.
149 These programs enable you to find the files in one or more directory
150 trees that:
152 @itemize @bullet
153 @item
154 have names that contain certain text or match a certain pattern;
155 @item
156 are links to certain files;
157 @item
158 were last used during a certain period of time;
159 @item
160 are within a certain size range;
161 @item
162 are of a certain type (regular file, directory, symbolic link, etc.);
163 @item
164 are owned by a certain user or group;
165 @item
166 have certain access permissions;
167 @item
168 contain text that matches a certain pattern;
169 @item
170 are within a certain depth in the directory tree;
171 @item
172 or some combination of the above.
173 @end itemize
175 Once you have found the files you're looking for (or files that are
176 potentially the ones you're looking for), you can do more to them than
177 simply list their names.  You can get any combination of the files'
178 attributes, or process the files in many ways, either individually or
179 in groups of various sizes.  Actions that you might want to perform on
180 the files you have found include, but are not limited to:
182 @itemize @bullet
183 @item
184 view or edit
185 @item
186 store in an archive
187 @item
188 remove or rename
189 @item
190 change access permissions
191 @item
192 classify into groups
193 @end itemize
195 This manual describes how to perform each of those tasks, and more.
197 @node Overview
198 @section Overview
200 The principal programs used for making lists of files that match given
201 criteria and running commands on them are @code{find}, @code{locate},
202 and @code{xargs}.  An additional command, @code{updatedb}, is used by
203 system administrators to create databases for @code{locate} to use.
205 @code{find} searches for files in a directory hierarchy and prints
206 information about the files it found.  It is run like this:
208 @example
209 find @r{[}@var{file}@dots{}@r{]} @r{[}@var{expression}@r{]}
210 @end example
212 @noindent
213 Here is a typical use of @code{find}.  This example prints the names
214 of all files in the directory tree rooted in @file{/usr/src} whose
215 name ends with @samp{.c} and that are larger than 100 Kilobytes.
216 @example
217 find /usr/src -name '*.c' -size +100k -print
218 @end example
220 Notice that the wildcard must be enclosed in quotes in order to
221 protect it from expansion by the shell.
223 @code{locate} searches special file name databases for file names that
224 match patterns.  The system administrator runs the @code{updatedb}
225 program to create the databases.  @code{locate} is run like this:
227 @example
228 locate @r{[}@var{option}@dots{}@r{]} @var{pattern}@dots{}
229 @end example
231 @noindent
232 This example prints the names of all files in the default file name
233 database whose name ends with @samp{Makefile} or @samp{makefile}.
234 Which file names are stored in the database depends on how the system
235 administrator ran @code{updatedb}.
236 @example
237 locate '*[Mm]akefile'
238 @end example
240 The name @code{xargs}, pronounced EX-args, means ``combine
241 arguments.''  @code{xargs} builds and executes command lines by
242 gathering together arguments it reads on the standard input.  Most
243 often, these arguments are lists of file names generated by
244 @code{find}.  @code{xargs} is run like this:
246 @example
247 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
248 @end example
250 @noindent
251 The following command searches the files listed in the file
252 @file{file-list} and prints all of the lines in them that contain the
253 word @samp{typedef}.
254 @example
255 xargs grep typedef < file-list
256 @end example
258 @node find Expressions
259 @section @code{find} Expressions
261 The expression that @code{find} uses to select files consists of one
262 or more @dfn{primaries}, each of which is a separate command line
263 argument to @code{find}.  @code{find} evaluates the expression each
264 time it processes a file.  An expression can contain any of the
265 following types of primaries:
267 @table @dfn
268 @item options
269 affect overall operation rather than the processing of a specific
270 file;
271 @item tests
272 return a true or false value, depending on the file's attributes;
273 @item actions
274 have side effects and return a true or false value; and
275 @item operators
276 connect the other arguments and affect when and whether they are
277 evaluated.
278 @end table
280 You can omit the operator between two primaries; it defaults to
281 @samp{-and}.  @xref{Combining Primaries With Operators}, for ways to
282 connect primaries into more complex expressions.  If the expression
283 contains no actions other than @samp{-prune}, @samp{-print} is
284 performed on all files for which the entire expression is true
285 (@pxref{Print File Name}).
287 Options take effect immediately, rather than being evaluated for each
288 file when their place in the expression is reached.  Therefore, for
289 clarity, it is best to place them at the beginning of the expression.
291 Many of the primaries take arguments, which immediately follow them in
292 the next command line argument to @code{find}.  Some arguments are
293 file names, patterns, or other strings; others are numbers.  Numeric
294 arguments can be specified as
296 @table @code
297 @item +@var{n}
298 for greater than @var{n},
299 @item -@var{n}
300 for less than @var{n},
301 @item @var{n}
302 for exactly @var{n}.
303 @end table
305 @node Finding Files, Actions, Introduction, Top
306 @chapter Finding Files
308 By default, @code{find} prints to the standard output the names of the
309 files that match the given criteria.  @xref{Actions}, for how to get
310 more information about the matching files.
313 @menu
314 * Name::
315 * Links::
316 * Time::
317 * Size::
318 * Type::
319 * Owner::
320 * Permissions::
321 * Contents::
322 * Directories::
323 * Filesystems::
324 * Combining Primaries With Operators::
325 @end menu
327 @node Name
328 @section Name
330 Here are ways to search for files whose name matches a certain
331 pattern.  @xref{Shell Pattern Matching}, for a description of the
332 @var{pattern} arguments to these tests.
334 Each of these tests has a case-sensitive version and a
335 case-insensitive version, whose name begins with @samp{i}.  In a
336 case-insensitive comparison, the patterns @samp{fo*} and @samp{F??}
337 match the file names @file{Foo}, @samp{FOO}, @samp{foo}, @samp{fOo},
338 etc.
340 @menu
341 * Base Name Patterns::
342 * Full Name Patterns::
343 * Fast Full Name Search::
344 * Shell Pattern Matching::      Wildcards used by these programs.
345 @end menu
347 @node Base Name Patterns
348 @subsection Base Name Patterns
350 @deffn Test -name pattern
351 @deffnx Test -iname pattern
352 True if the base of the file name (the path with the leading
353 directories removed) matches shell pattern @var{pattern}.  For
354 @samp{-iname}, the match is case-insensitive.  To ignore a whole
355 directory tree, use @samp{-prune} (@pxref{Directories}).  As an
356 example, to find Texinfo source files in @file{/usr/local/doc}:
358 @example
359 find /usr/local/doc -name '*.texi'
360 @end example
361 @end deffn
363 Notice that the wildcard must be enclosed in quotes in order to
364 protect it from expansion by the shell.
366 Patterns for @samp{-name} and @samp{-iname} will match a file name
367 with a leading @samp{.}.  For example the command @samp{find /tmp
368 -name \*bar} will match the file @file{/tmp/.foobar}.
371 @node Full Name Patterns
372 @subsection Full Name Patterns
374 @deffn Test -wholename pattern
375 @deffnx Test -iwholename pattern
376 True if the entire file name, starting with the command line argument
377 under which the file was found, matches shell pattern @var{pattern}.
378 For @samp{-iwholename}, the match is case-insensitive.  To ignore a
379 whole directory tree, use @samp{-prune} rather than checking every
380 file in the tree (@pxref{Directories}).  The ``entire file name'' as
381 used by @code{find} starts with the starting-point specified on the
382 command line, and is not converted to an absolute pathname, so for
383 example @code{cd /; find tmp -wholename /tmp} will never match
384 anything.
385 @end deffn
387 @deffn Test -path pattern
388 @deffnx Test -ipath pattern
389 These tests are deprecated, but work as for @samp{-wholename} and
390 @samp{-iwholename}, respectively.  The @samp{-ipath} test is a GNU
391 extension, but @samp{-path} is also provided by HP-UX @code{find}.
392 @end deffn
394 @deffn Test -regex expr
395 @deffnx Test -iregex expr
396 True if the entire file name matches regular expression @var{expr}.
397 This is a match on the whole path, not a search.  For example, to
398 match a file named @file{./fubar3}, you can use the regular expression
399 @samp{.*bar.} or @samp{.*b.*3}, but not @samp{f.*r3}.  @xref{Regexps,
400 , Syntax of Regular Expressions, emacs, The GNU Emacs Manual}, for a
401 description of the syntax of regular expressions.  For @samp{-iregex},
402 the match is case-insensitive.  There are several varieties of regular
403 expressions; by default this test uses POSIX basic regular
404 expressions, but this can be changed with the option
405 @samp{-regextype}.
406 @end deffn
408 @deffn Option -regextype name
409 This option controls the variety of regular expression syntax
410 understood by the @samp{-regex} and @samp{-iregex} tests.  This option
411 is positional; that is, it only affects regular expressions which
412 occur later in the command line.  If this option is not given, GNU
413 Emacs regular expressions are assumed.  Currently-implemented types
417 @table @samp
418 @item emacs
419 Regular expressions compatible with GNU Emacs; this is also the
420 default behaviour if this option is not used.
421 @item posix-awk
422 Regular expressions compatible with the POSIX awk command (not GNU awk)
423 @item posix-basic
424 POSIX Basic Regular Expressions.
425 @item posix-egrep
426 Regular expressions compatible with the POSIX egrep command
427 @item posix-extended
428 POSIX Extended Regular Expressions
429 @end table
431 @ref{Regular Expressions} for more information on the regular
432 expression dialects understood by GNU findutils.
435 @end deffn
437 @node Fast Full Name Search
438 @subsection Fast Full Name Search
440 To search for files by name without having to actually scan the
441 directories on the disk (which can be slow), you can use the
442 @code{locate} program.  For each shell pattern you give it,
443 @code{locate} searches one or more databases of file names and
444 displays the file names that contain the pattern.  @xref{Shell Pattern
445 Matching}, for details about shell patterns.
447 If a pattern is a plain string---it contains no
448 metacharacters---@code{locate} displays all file names in the database
449 that contain that string.  If a pattern contains
450 metacharacters, @code{locate} only displays file names that match the
451 pattern exactly.  As a result, patterns that contain metacharacters
452 should usually begin with a @samp{*}, and will most often end with one
453 as well.  The exceptions are patterns that are intended to explicitly
454 match the beginning or end of a file name.
456 If you only want @code{locate} to match against the last component of
457 the file names (the ``base name'' of the files) you can use the
458 @samp{--basename} option.  The opposite behaviour is the default, but
459 can be selected explicitly by using the option @samp{--wholename}.
461 The command
462 @example
463 locate @var{pattern}
464 @end example
466 is almost equivalent to
467 @example
468 find @var{directories} -name @var{pattern}
469 @end example
471 where @var{directories} are the directories for which the file name
472 databases contain information.  The differences are that the
473 @code{locate} information might be out of date, and that @code{locate}
474 handles wildcards in the pattern slightly differently than @code{find}
475 (@pxref{Shell Pattern Matching}).
477 The file name databases contain lists of files that were on the system
478 when the databases were last updated.  The system administrator can
479 choose the file name of the default database, the frequency with which
480 the databases are updated, and the directories for which they contain
481 entries.
483 Here is how to select which file name databases @code{locate}
484 searches.  The default is system-dependent.
486 @table @code
487 @item --database=@var{path}
488 @itemx -d @var{path}
489 Instead of searching the default file name database, search the file
490 name databases in @var{path}, which is a colon-separated list of
491 database file names.  You can also use the environment variable
492 @code{LOCATE_PATH} to set the list of database files to search.  The
493 option overrides the environment variable if both are used.
494 @end table
496 @node Shell Pattern Matching
497 @subsection Shell Pattern Matching
499 @code{find} and @code{locate} can compare file names, or parts of file
500 names, to shell patterns.  A @dfn{shell pattern} is a string that may
501 contain the following special characters, which are known as
502 @dfn{wildcards} or @dfn{metacharacters}.
504 You must quote patterns that contain metacharacters to prevent the
505 shell from expanding them itself.  Double and single quotes both work;
506 so does escaping with a backslash.
508 @table @code
509 @item *
510 Matches any zero or more characters.
512 @item ?
513 Matches any one character.
515 @item [@var{string}]
516 Matches exactly one character that is a member of the string
517 @var{string}.  This is called a @dfn{character class}.  As a
518 shorthand, @var{string} may contain ranges, which consist of two
519 characters with a dash between them.  For example, the class
520 @samp{[a-z0-9_]} matches a lowercase letter, a number, or an
521 underscore.  You can negate a class by placing a @samp{!} or @samp{^}
522 immediately after the opening bracket.  Thus, @samp{[^A-Z@@]} matches
523 any character except an uppercase letter or an at sign.
525 @item \
526 Removes the special meaning of the character that follows it.  This
527 works even in character classes.
528 @end table
530 In the @code{find} tests that do shell pattern matching (@samp{-name},
531 @samp{-wholename}, etc.), wildcards in the pattern will match a
532 @samp{.}  at the beginning of a file name.  This is also the case for
533 @code{locate}.  Thus, @samp{find -name '*macs'} will match a file
534 named @file{.emacs}, as will @samp{locate '*macs'}.
536 Slash characters have no special significance in the shell pattern
537 matching that @code{find} and @code{locate} do, unlike in the shell,
538 in which wildcards do not match them.  Therefore, a pattern
539 @samp{foo*bar} can match a file name @samp{foo3/bar}, and a pattern
540 @samp{./sr*sc} can match a file name @samp{./src/misc}.
542 If you want to locate some files with the @samp{locate} command but
543 don't need to see the full list you can use the @samp{--limit} option
544 to see just a small number of results, or the @samp{--count} option to
545 display only the total number of matches.
547 @node Links
548 @section Links
550 There are two ways that files can be linked together.  @dfn{Symbolic
551 links} are a special type of file whose contents are a portion of the
552 name of another file.  @dfn{Hard links} are multiple directory entries
553 for one file; the file names all have the same index node
554 (@dfn{inode}) number on the disk.
556 @menu
557 * Symbolic Links::
558 * Hard Links::
559 @end menu
561 @node Symbolic Links
562 @subsection Symbolic Links
564 Symbolic links are names that reference other files.  GNU @code{find}
565 will handle symbolic links in one of two ways; firstly, it can
566 dereference the links for you - this means that if it comes across a
567 symbolic link, it examines the file that the link points to, in order
568 to see if it matches the criteria you have specified.  Secondly, it
569 can check the link itself in case you might be looking for the actual
570 link.  If the file that the symbolic link points to is also within the
571 directory hierarchy you are searching with the @code{find} command,
572 you may not see a great deal of difference between these two
573 alternatives.
575 By default, @code{find} examines symbolic links themselves when it
576 finds them (and, if it later comes across the linked-to file, it will
577 examine that, too).  If you would prefer @code{find} to dereference
578 the links and examine the file that each link points to, specify the
579 @samp{-L} option to @code{find}.  You can explicitly specify the
580 default behaviour by using the @samp{-P} option.  The @samp{-H}
581 option is a half-way-between option which ensures that any symbolic
582 links listed on the command line are dereferenced, but other symbolic
583 links are not.
585 Symbolic links are different to ``hard links'' in the sense that you
586 need permissions upon the linked-to file in order to be able to
587 dereference the link.  This can mean that even if you specify the
588 @samp{-L} option, @code{find} may not be able to determine the
589 properties of the file that the link points to (because you don't have
590 sufficient permissions).  In this situation, @code{find} uses the
591 properties of the link itself.  This also occurs if a symbolic link
592 exists but points to a file that is missing.
594 The options controlling the behaviour of @code{find} with respect to
595 links are as follows :-
597 @table @samp
598 @item -P
599 @code{find} does not dereference symbolic links at all.  This is the
600 default behaviour.  This option must be specified before any of the
601 file names on the command line.
602 @item -H
603 @code{find} does not dereference symbolic links (except in the case of
604 file names on the command line, which are dereferenced).  If a
605 symbolic link cannot be dereferenced, the information for the symbolic
606 link itself is used.  This option must be specified before any of the
607 file names on the command line.
608 @item -L
609 @code{find} dereferences symbolic links where possible, and where this
610 is not possible it uses the properties of the symbolic link itself.
611 This option must be specified before any of the file names on the
612 command line.  Use of this option also implies the same behaviour as
613 the @samp{-noleaf} option.  If you later use the @samp{-H} or
614 @samp{-P} options, this does not turn off @samp{-noleaf}.
616 @item -follow
617 This option forms part of the ``expression'' and must be specified
618 after the file names, but it is otherwise equivalent to @samp{-L}.
619 @end table
621 The following differences in behavior occur when the @samp{-L} option
622 is used:
624 @itemize @bullet
625 @item
626 @code{find} follows symbolic links to directories when searching
627 directory trees.
628 @item
629 @samp{-lname} and @samp{-ilname} always return false (unless they
630 happen to match broken symbolic links).
631 @item
632 @samp{-type} reports the types of the files that symbolic links point
634 @item
635 Implies @samp{-noleaf} (@pxref{Directories}).
636 @end itemize
638 If the @samp{-L} option or the @samp{-H} option is used,
639 the file names used as arguments to @samp{-newer}, @samp{-anewer}, and
640 @samp{-cnewer} are dereferenced and the timestamp from the pointed-to
641 file is used instead (if possible -- otherwise the timestamp from the
642 symbolic link is used).
644 @deffn Test -lname pattern
645 @deffnx Test -ilname pattern
646 True if the file is a symbolic link whose contents match shell pattern
647 @var{pattern}.  For @samp{-ilname}, the match is case-insensitive.
648 @xref{Shell Pattern Matching}, for details about the @var{pattern}
649 argument.  If the @samp{-L} option is in effect, this test will always
650 return false for symbolic links unless they are broken.  So, to list
651 any symbolic links to @file{sysdep.c} in the current directory and its
652 subdirectories, you can do:
654 @example
655 find . -lname '*sysdep.c'
656 @end example
657 @end deffn
659 @node Hard Links
660 @subsection Hard Links
662 Hard links allow more than one name to refer to the same file.  To
663 find all the names which refer to the same file as NAME, use
664 @samp{-samefile NAME}.  If you are not using the @samp{-L} option, you
665 can confine your search to one filesystem using the @samp{-xdev}
666 option.  This is useful because hard links cannot point outside a
667 single filesystem, so this can cut down on needless searching.
669 If the @samp{-L} option is in effect, and NAME is in fact a symbolic
670 link, the symbolic link will be dereferenced.  Hence you are searching
671 for other links (hard or symbolic) to the file pointed to by NAME.  If
672 @samp{-L} is in effect but NAME is not itself a symbolic link, other
673 symbolic links to the file NAME will be matched.
675 You can also search for files by inode number.  This can occasionally
676 be useful in diagnosing problems with filesystems for example, because
677 @code{fsck} tends to print inode numbers.  Inode numbers also
678 occasionally turn up in log messages for some types of software, and
679 are used to support the @code{ftok()} library function.
681 You can learn a file's inode number and the number of links to it by
682 running @samp{ls -li} or @samp{find -ls}.
684 You can search for hard links to inode number NUM by using @samp{-inum
685 NUM}. If there are any filesystem mount points below the directory
686 where you are starting the search, use the @samp{-xdev} option unless
687 you are also using the @samp{-L} option.  Using @samp{-xdev} this
688 saves needless searching, since hard links to a file must be on the
689 same filesystem.  @xref{Filesystems}.
691 @deffn Test -samefile NAME
692 File is a hard link to the same inode as NAME.  If the @samp{-L}
693 option is in effect, symbolic links to the same file as NAME points to
694 are also matched.
695 @end deffn
697 @deffn Test -inum n
698 File has inode number @var{n}.  The @samp{+} and @samp{-} qualifiers
699 also work, though these are rarely useful.
700 @end deffn
702 You can also search for files that have a certain number of links,
703 with @samp{-links}.  Directories normally have at least two hard
704 links; their @file{.} entry is the second one.  If they have
705 subdirectories, each of those also has a hard link called @file{..} to
706 its parent directory.  The @file{.} and @file{..} directory entries
707 are not normally searched unless they are mentioned on the @code{find}
708 command line.
710 @deffn Test -links n
711 File has @var{n} hard links.
712 @end deffn
714 @deffn Test -links +n
715 File has more than @var{n} hard links.
716 @end deffn
718 @deffn Test -links -n
719 File has fewer than @var{n} hard links.
720 @end deffn
722 @node Time
723 @section Time
725 Each file has three time stamps, which record the last time that
726 certain operations were performed on the file:
728 @enumerate
729 @item
730 access (read the file's contents)
731 @item
732 change the status (modify the file or its attributes)
733 @item
734 modify (change the file's contents)
735 @end enumerate
737 There is no timestamp that indicates when a file was @emph{created}.
739 You can search for files whose time stamps are within a certain age
740 range, or compare them to other time stamps.
742 @menu
743 * Age Ranges::
744 * Comparing Timestamps::
745 @end menu
747 @node Age Ranges
748 @subsection Age Ranges
750 These tests are mainly useful with ranges (@samp{+@var{n}} and
751 @samp{-@var{n}}).
753 @deffn Test -atime n
754 @deffnx Test -ctime n
755 @deffnx Test -mtime n
756 True if the file was last accessed (or its status changed, or it was
757 modified) @var{n}*24 hours ago.  The number of 24-hour periods since
758 the file's timestamp is always rounded down; therefore 0 means ``less
759 than 24 hours ago'', 1 means ``between 24 and 48 hours ago'', and so
760 forth.
761 @end deffn
763 @deffn Test -amin n
764 @deffnx Test -cmin n
765 @deffnx Test -mmin n
766 True if the file was last accessed (or its status changed, or it was
767 modified) @var{n} minutes ago.  These tests provide finer granularity
768 of measurement than @samp{-atime} et al., but rounding is done in a
769 similar way.  For example, to list files in @file{/u/bill} that were
770 last read from 2 to 6 minutes ago:
772 @example
773 find /u/bill -amin +2 -amin -6
774 @end example
775 @end deffn
777 @deffn Option -daystart
778 Measure times from the beginning of today rather than from 24 hours
779 ago.  So, to list the regular files in your home directory that were
780 modified yesterday, do
782 @example
783 find ~ -daystart -type f -mtime 1
784 @end example
785 @end deffn
787 The @samp{-daystart} option is unlike most other options in that it
788 has an effect on the way that other tests are performed.  The affected
789 tests are @samp{-amin}, @samp{-cmin}, @samp{-mmin}, @samp{-atime},
790 @samp{-ctime} and @samp{-mtime}.
792 @node Comparing Timestamps
793 @subsection Comparing Timestamps
795 As an alternative to comparing timestamps to the current time, you can
796 compare them to another file's timestamp.  That file's timestamp could
797 be updated by another program when some event occurs.  Or you could
798 set it to a particular fixed date using the @code{touch} command.  For
799 example, to list files in @file{/usr} modified after February 1 of the
800 current year:
802 @c Idea from Rick Sladkey.
803 @example
804 touch -t 02010000 /tmp/stamp$$
805 find /usr -newer /tmp/stamp$$
806 rm -f /tmp/stamp$$
807 @end example
809 @deffn Test -anewer file
810 @deffnx Test -cnewer file
811 @deffnx Test -newer file
812 True if the file was last accessed (or its status changed, or it was
813 modified) more recently than @var{file} was modified.  These tests are
814 affected by @samp{-follow} only if @samp{-follow} comes before them on
815 the command line.  @xref{Symbolic Links}, for more information on
816 @samp{-follow}.  As an example, to list any files modified since
817 @file{/bin/sh} was last modified:
819 @example
820 find . -newer /bin/sh
821 @end example
822 @end deffn
824 @deffn Test -used n
825 True if the file was last accessed @var{n} days after its status was
826 last changed.  Useful for finding files that are not being used, and
827 could perhaps be archived or removed to save disk space.
828 @end deffn
830 @node Size
831 @section Size
833 @deffn Test -size n@r{[}bckwMG@r{]}
834 True if the file uses @var{n} units of space, rounding up.  The units
835 are 512-byte blocks by default, but they can be changed by adding a
836 one-character suffix to @var{n}:
838 @table @code
839 @item b
840 512-byte blocks (never 1024)
841 @item c
842 bytes
843 @item k
844 kilobytes (1024 bytes)
845 @item w
846 2-byte words
847 @item M
848 Megabytes
849 @item G
850 Gigabytes
851 @end table
853 The `b' suffix always considers blocks to be 512 bytes.  This is not
854 affected by the setting (or non-setting) of the POSIXLY_CORRECT
855 environment variable.  This behaviour is different to the behaviour of
856 the @samp{-ls} action).  If you want to use 1024-byte units, use the
857 `k' suffix instead.
859 The number can be prefixed with a `+' or a `-'.  A plus sign indicates
860 that the test should succeed if the file uses at least @var{n} units
861 of storage (a common use of this test) and a minus sign
862 indicates that the test should succeed if the file uses less than
863 @var{n} units of storage.  There is no `=' prefix, because that's the
864 default anyway.
866 The size does not count indirect blocks, but it does count blocks in
867 sparse files that are not actually allocated.  In other words, it's
868 consistent with the result you get for @samp{ls -l} or @samp{wc -c}.
869 This handling of sparse files differs from the output of the @samp{%k}
870 and @samp{%b} format specifiers for the @samp{-printf} predicate.
872 @end deffn
874 @deffn Test -empty
875 True if the file is empty and is either a regular file or a directory.
876 This might help determine good candidates for deletion.  This test is
877 useful with @samp{-depth} (@pxref{Directories}) and @samp{-delete}
878 (@pxref{Single File}).
879 @end deffn
881 @node Type
882 @section Type
884 @deffn Test -type c
885 True if the file is of type @var{c}:
887 @table @code
888 @item b
889 block (buffered) special
890 @item c
891 character (unbuffered) special
892 @item d
893 directory
894 @item p
895 named pipe (FIFO)
896 @item f
897 regular file
898 @item l
899 symbolic link
900 @item s
901 socket
902 @item D
903 door (Solaris)
904 @end table
905 @end deffn
907 @deffn Test -xtype c
908 The same as @samp{-type} unless the file is a symbolic link.  For
909 symbolic links: if @samp{-follow} has not been given, true if the file
910 is a link to a file of type @var{c}; if @samp{-follow} has been given,
911 true if @var{c} is @samp{l}.  In other words, for symbolic links,
912 @samp{-xtype} checks the type of the file that @samp{-type} does not
913 check.  @xref{Symbolic Links}, for more information on @samp{-follow}.
914 @end deffn
916 @node Owner
917 @section Owner
919 @deffn Test -user uname
920 @deffnx Test -group gname
921 True if the file is owned by user @var{uname} (belongs to group
922 @var{gname}).  A numeric ID is allowed.
923 @end deffn
925 @deffn Test -uid n
926 @deffnx Test -gid n
927 True if the file's numeric user ID (group ID) is @var{n}.  These tests
928 support ranges (@samp{+@var{n}} and @samp{-@var{n}}), unlike
929 @samp{-user} and @samp{-group}.
930 @end deffn
932 @deffn Test -nouser
933 @deffnx Test -nogroup
934 True if no user corresponds to the file's numeric user ID (no group
935 corresponds to the numeric group ID).  These cases usually mean that
936 the files belonged to users who have since been removed from the
937 system.  You probably should change the ownership of such files to an
938 existing user or group, using the @code{chown} or @code{chgrp}
939 program.
940 @end deffn
942 @node Permissions
943 @section Permissions
945 @xref{File Permissions}, for information on how file permissions are
946 structured and how to specify them.
948 @deffn Test -perm mode
950 True if the file's permissions are exactly @var{mode}, which can be
951 numeric or symbolic.
953 If @var{mode} starts with @samp{-}, true if
954 @emph{all} of the permissions set in @var{mode} are set for the file;
955 permissions not set in @var{mode} are ignored.
956 If @var{mode} starts with @samp{/}, true if
957 @emph{any} of the permissions set in @var{mode} are set for the file;
958 permissions not set in @var{mode} are ignored.
959 This is a GNU extension.
961 If you don't use the @samp{/} or @samp{-} form with a symbolic mode
962 string, you may have to specify a rather complex mode string.  For
963 example @samp{-perm g=w} will only match files which have mode 0020
964 (that is, ones for which group write permission is the only permission
965 set).  It is more likely that you will want to use the @samp{/} or
966 @samp{-} forms, for example @samp{-perm -g=w}, which matches any file
967 with group write permission.
970 @table @samp
971 @item -perm 664
972 Match files which have read and write permission for their owner,
973 and group, but which the rest of the world can read but not write to.
974 Files which meet these criteria but have other permissions bits set
975 (for example if someone can execute the file) will not be matched.
977 @item -perm -664
978 Match files which have read and write permission for their owner,
979 and group, but which the rest of the world can read but not write to,
980 without regard to the presence of any extra permission bits (for
981 example the executable bit).  This will match a file which has mode
982 0777, for example.
984 @item -perm /222
985 Match files which are writeable by somebody (their owner, or
986 their group, or anybody else).
988 @item -perm /022
989 Match files which are writeable by either their owner or their
990 group.  The files don't have to be writeable by both the owner and
991 group to be matched; either will do.
993 @item -perm /g+w,o+w
994 As above.
996 @item -perm /g=w,o=w
997 As above
999 @item -perm -022
1000 Search for files which are writeable by both their owner and their
1001 group.
1003 @item -perm -g+w,o+w
1004 As above.
1005 @end table
1006 @end deffn
1008 @node Contents
1009 @section Contents
1011 To search for files based on their contents, you can use the
1012 @code{grep} program.  For example, to find out which C source files in
1013 the current directory contain the string @samp{thing}, you can do:
1015 @example
1016 grep -l thing *.[ch]
1017 @end example
1019 If you also want to search for the string in files in subdirectories,
1020 you can combine @code{grep} with @code{find} and @code{xargs}, like
1021 this:
1023 @example
1024 find . -name '*.[ch]' | xargs grep -l thing
1025 @end example
1027 The @samp{-l} option causes @code{grep} to print only the names of
1028 files that contain the string, rather than the lines that contain it.
1029 The string argument (@samp{thing}) is actually a regular expression,
1030 so it can contain metacharacters.  This method can be refined a little
1031 by using the @samp{-r} option to make @code{xargs} not run @code{grep}
1032 if @code{find} produces no output, and using the @code{find} action
1033 @samp{-print0} and the @code{xargs} option @samp{-0} to avoid
1034 misinterpreting files whose names contain spaces:
1036 @example
1037 find . -name '*.[ch]' -print0 | xargs -r -0 grep -l thing
1038 @end example
1040 For a fuller treatment of finding files whose contents match a
1041 pattern, see the manual page for @code{grep}.
1043 @node Directories
1044 @section Directories
1046 Here is how to control which directories @code{find} searches, and how
1047 it searches them.  These two options allow you to process a horizontal
1048 slice of a directory tree.
1050 @deffn Option -maxdepth levels
1051 Descend at most @var{levels} (a non-negative integer) levels of
1052 directories below the command line arguments.  @samp{-maxdepth 0}
1053 means only apply the tests and actions to the command line arguments.
1054 @end deffn
1056 @deffn Option -mindepth levels
1057 Do not apply any tests or actions at levels less than @var{levels} (a
1058 non-negative integer).  @samp{-mindepth 1} means process all files
1059 except the command line arguments.
1060 @end deffn
1062 @deffn Option -depth
1063 Process each directory's contents before the directory itself.  Doing
1064 this is a good idea when producing lists of files to archive with
1065 @code{cpio} or @code{tar}.  If a directory does not have write
1066 permission for its owner, its contents can still be restored from the
1067 archive since the directory's permissions are restored after its
1068 contents.
1069 @end deffn
1071 @deffn Option -d
1072 This is a deprecated synonym for @samp{-depth}, for compatibility with
1073 Mac OS X, FreeBSD and OpenBSD.  The @samp{-depth} option is a POSIX
1074 feature, so it is better to use that.
1075 @end deffn
1077 @deffn Action -prune
1078 If the file is a directory, do not descend into it.  The result is
1079 true.  For example, to skip the directory @file{src/emacs} and all
1080 files and directories under it, and print the names of the other files
1081 found:
1083 @example
1084 find . -wholename './src/emacs' -prune -o -print
1085 @end example
1087 The above command will not print @file{./src/emacs} among its list of
1088 results.  This however is not due to the effect of the @samp{-prune}
1089 action (which only prevents further descent, it doesn't make sure we
1090 ignore that item).  Instead, this effect is due to the use of
1091 @samp{-o}.  Since the left hand side of the ``or'' condition has
1092 succeeded for @file{./src/emacs}, it is not necessary to evaluate the
1093 right-hand-side (@samp{-print}) at all for this particular file.  If
1094 you wanted to print that directory name you could use either an extra
1095 @samp{-print} action:
1097 @example
1098 find . -wholename './src/emacs' -prune -print -o -print
1099 @end example
1101 or use the comma operator:
1103 @example
1104 find . -wholename './src/emacs' -prune , -print
1105 @end example
1107 If the @samp{-depth} option is in effect, the subdirectories will have
1108 already been visited in any case.  Hence @samp{-prune} has no effect
1109 and returns false.
1110 @end deffn
1113 @deffn Action -quit
1114 Exit immediately (with return value zero if no errors have occurred).
1115 No child processes will be left running, but no more files specified
1116 on the command line will be processed.  For example, @code{find
1117 /tmp/foo /tmp/bar -print -quit} will print only @samp{/tmp/foo}.
1118 @end deffn
1120 @deffn Option -noleaf
1121 Do not optimize by assuming that directories contain 2 fewer
1122 subdirectories than their hard link count.  This option is needed when
1123 searching filesystems that do not follow the Unix directory-link
1124 convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount
1125 points.  Each directory on a normal Unix filesystem has at least 2
1126 hard links: its name and its @file{.}  entry.  Additionally, its
1127 subdirectories (if any) each have a @file{..}  entry linked to that
1128 directory.  When @code{find} is examining a directory, after it has
1129 statted 2 fewer subdirectories than the directory's link count, it
1130 knows that the rest of the entries in the directory are
1131 non-directories (@dfn{leaf} files in the directory tree).  If only the
1132 files' names need to be examined, there is no need to stat them; this
1133 gives a significant increase in search speed.
1134 @end deffn
1136 @deffn Option -ignore_readdir_race
1137 If a file disappears after its name has been read from a directory but
1138 before @code{find} gets around to examining the file with @code{stat},
1139 don't issue an error message.  If you don't specify this option, an
1140 error message will be issued.  This option can be useful in system
1141 scripts (cron scripts, for example) that examine areas of the
1142 filesystem that change frequently (mail queues, temporary directories,
1143 and so forth), because this scenario is common for those sorts of
1144 directories.  Completely silencing error messages from @code{find} is
1145 undesirable, so this option neatly solves the problem.  There is no
1146 way to search one part of the filesystem with this option on and part
1147 of it with this option off, though.
1148 @end deffn
1150 @deffn Option -noignore_readdir_race
1151 This option reverses the effect of the @samp{-ignore_readdir_race}
1152 option.
1153 @end deffn
1156 @node Filesystems
1157 @section Filesystems
1159 A @dfn{filesystem} is a section of a disk, either on the local host or
1160 mounted from a remote host over a network.  Searching network
1161 filesystems can be slow, so it is common to make @code{find} avoid
1162 them.
1164 There are two ways to avoid searching certain filesystems.  One way is
1165 to tell @code{find} to only search one filesystem:
1167 @deffn Option -xdev
1168 @deffnx Option -mount
1169 Don't descend directories on other filesystems.  These options are
1170 synonyms.
1171 @end deffn
1173 The other way is to check the type of filesystem each file is on, and
1174 not descend directories that are on undesirable filesystem types:
1176 @deffn Test -fstype type
1177 True if the file is on a filesystem of type @var{type}.  The valid
1178 filesystem types vary among different versions of Unix; an incomplete
1179 list of filesystem types that are accepted on some version of Unix or
1180 another is:
1181 @example
1182 ext2 ext3 proc sysfs ufs 4.2 4.3 nfs tmp mfs S51K S52K
1183 @end example
1184 You can use @samp{-printf} with the @samp{%F} directive to see the
1185 types of your filesystems.  The @samp{%D} directive shows the device
1186 number.  @xref{Print File Information}.  @samp{-fstype} is usually
1187 used with @samp{-prune} to avoid searching remote filesystems
1188 (@pxref{Directories}).
1189 @end deffn
1191 @node Combining Primaries With Operators
1192 @section Combining Primaries With Operators
1194 Operators build a complex expression from tests and actions.
1195 The operators are, in order of decreasing precedence:
1197 @table @code
1198 @item @asis{( @var{expr} )}
1199 @findex ()
1200 Force precedence.  True if @var{expr} is true.
1202 @item @asis{! @var{expr}}
1203 @itemx @asis{-not @var{expr}}
1204 @findex !
1205 @findex -not
1206 True if @var{expr} is false.
1208 @item @asis{@var{expr1 expr2}}
1209 @itemx @asis{@var{expr1} -a @var{expr2}}
1210 @itemx @asis{@var{expr1} -and @var{expr2}}
1211 @findex -a
1212 @findex -and
1213 And; @var{expr2} is not evaluated if @var{expr1} is false.
1215 @item @asis{@var{expr1} -o @var{expr2}}
1216 @itemx @asis{@var{expr1} -or @var{expr2}}
1217 @findex -o
1218 @findex -or
1219 Or; @var{expr2} is not evaluated if @var{expr1} is true.
1221 @item @asis{@var{expr1} , @var{expr2}}
1222 @findex ,
1223 List; both @var{expr1} and @var{expr2} are always evaluated.  True if
1224 @var{expr2} is true.  The value of @var{expr1} is discarded.  This
1225 operator lets you do multiple independent operations on one traversal,
1226 without depending on whether other operations succeeded.  The two
1227 operations @var{expr1} and @var{expr2} are not always fully
1228 independent, since @var{expr1} might have side effects like touching
1229 or deleting files, or it might use @samp{-prune} which would also
1230 affect @var{expr2}.
1231 @end table
1233 @code{find} searches the directory tree rooted at each file name by
1234 evaluating the expression from left to right, according to the rules
1235 of precedence, until the outcome is known (the left hand side is false
1236 for @samp{-and}, true for @samp{-or}), at which point @code{find}
1237 moves on to the next file name.
1239 There are two other tests that can be useful in complex expressions:
1241 @deffn Test -true
1242 Always true.
1243 @end deffn
1245 @deffn Test -false
1246 Always false.
1247 @end deffn
1249 @node Actions, Databases, Finding Files, Top
1250 @chapter Actions
1252 There are several ways you can print information about the files that
1253 match the criteria you gave in the @code{find} expression.  You can
1254 print the information either to the standard output or to a file that
1255 you name.  You can also execute commands that have the file names as
1256 arguments.  You can use those commands as further filters to select
1257 files.
1259 @menu
1260 * Print File Name::
1261 * Print File Information::
1262 * Run Commands::
1263 * Delete Files::
1264 * Adding Tests::
1265 @end menu
1267 @node Print File Name
1268 @section Print File Name
1270 @deffn Action -print
1271 True; print the entire file name on the standard output, followed by a
1272 newline.
1273 @end deffn
1275 @deffn Action -fprint file
1276 True; print the entire file name into file @var{file}, followed by a
1277 newline.  If @var{file} does not exist when @code{find} is run, it is
1278 created; if it does exist, it is truncated to 0 bytes.  The file names
1279 @file{/dev/stdout} and @file{/dev/stderr} are handled specially; they
1280 refer to the standard output and standard error output, respectively.
1281 @end deffn
1283 @node Print File Information
1284 @section Print File Information
1286 @deffn Action -ls
1287 True; list the current file in @samp{ls -dils} format on the standard
1288 output.  The output looks like this:
1290 @smallexample
1291 204744   17 -rw-r--r--   1 djm      staff       17337 Nov  2  1992 ./lwall-quotes
1292 @end smallexample
1294 The fields are:
1296 @enumerate
1297 @item
1298 The inode number of the file.  @xref{Hard Links}, for how to find
1299 files based on their inode number.
1301 @item
1302 the number of blocks in the file.  The block counts are of 1K blocks,
1303 unless the environment variable @code{POSIXLY_CORRECT} is set, in
1304 which case 512-byte blocks are used.  @xref{Size}, for how to find
1305 files based on their size.
1307 @item
1308 The file's type and permissions.  The type is shown as a dash for a
1309 regular file; for other file types, a letter like for @samp{-type} is
1310 used (@pxref{Type}).  The permissions are read, write, and execute for
1311 the file's owner, its group, and other users, respectively; a dash
1312 means the permission is not granted.  @xref{File Permissions}, for
1313 more details about file permissions.  @xref{Permissions}, for how to
1314 find files based on their permissions.
1316 @item
1317 The number of hard links to the file.
1319 @item
1320 The user who owns the file.
1322 @item
1323 The file's group.
1325 @item
1326 The file's size in bytes.
1328 @item
1329 The date the file was last modified.
1331 @item
1332 The file's name.  @samp{-ls} quotes non-printable characters in the
1333 file names using C-like backslash escapes.  This may change soon, as
1334 the treatment of unprintable characters is harmonised for @samp{-ls},
1335 @samp{-fls}, @samp{-print}, @samp{-fprint}, @samp{-printf} and
1336 @samp{-fprintf}.
1337 @end enumerate
1338 @end deffn
1340 @deffn Action -fls file
1341 True; like @samp{-ls} but write to @var{file} like @samp{-fprint}
1342 (@pxref{Print File Name}).
1343 @end deffn
1345 @deffn Action -printf format
1346 True; print @var{format} on the standard output, interpreting @samp{\}
1347 escapes and @samp{%} directives.  Field widths and precisions can be
1348 specified as with the @code{printf} C function.  Format flags (like
1349 @samp{#} for example) may not work as you expect because many of the
1350 fields, even numeric ones, are printed with %s.  This means though
1351 that the format flag @samp{-} will work; it forces left-alignment of
1352 the field.  Unlike @samp{-print}, @samp{-printf} does not add a
1353 newline at the end of the string.  If you want a newline at the end of
1354 the string, add a @samp{\n}.
1355 @end deffn
1357 @deffn Action -fprintf file format
1358 True; like @samp{-printf} but write to @var{file} like @samp{-fprint}
1359 (@pxref{Print File Name}).
1360 @end deffn
1362 @menu
1363 * Escapes::
1364 * Format Directives::
1365 * Time Formats::
1366 @end menu
1368 @node Escapes
1369 @subsection Escapes
1371 The escapes that @samp{-printf} and @samp{-fprintf} recognize are:
1373 @table @code
1374 @item \a
1375 Alarm bell.
1376 @item \b
1377 Backspace.
1378 @item \c
1379 Stop printing from this format immediately and flush the output.
1380 @item \f
1381 Form feed.
1382 @item \n
1383 Newline.
1384 @item \r
1385 Carriage return.
1386 @item \t
1387 Horizontal tab.
1388 @item \v
1389 Vertical tab.
1390 @item \\
1391 A literal backslash (@samp{\}).
1392 @item \NNN
1393 The character whose ASCII code is NNN (octal).
1394 @end table
1396 A @samp{\} character followed by any other character is treated as an
1397 ordinary character, so they both are printed, and a warning message is
1398 printed to the standard error output (because it was probably a typo).
1400 @node Format Directives
1401 @subsection Format Directives
1403 @samp{-printf} and @samp{-fprintf} support the following format
1404 directives to print information about the file being processed.  The C
1405 @code{printf} function, field width and precision specifiers are
1406 supported, as applied to string (%s) types. That is, you can specify
1407 "minimum field width"."maximum field width" for each directive.
1408 Format flags (like @samp{#} for example) may not work as you expect
1409 because many of the fields, even numeric ones, are printed with %s.
1410 The format flag @samp{-} does work; it forces left-alignment of the
1411 field.
1413 @samp{%%} is a literal percent sign.  A @samp{%} character followed by
1414 an unrecognised character (i.e. not a known directive or printf field
1415 width and precision specifier), is discarded (but the unrecognised
1416 character is printed), and a warning message is printed to the
1417 standard error output (because it was probably a typo).
1419 @menu
1420 * Name Directives::
1421 * Ownership Directives::
1422 * Size Directives::
1423 * Location Directives::
1424 * Time Directives::
1425 * Formatting Flags::
1426 @end menu
1428 @node Name Directives
1429 @subsubsection Name Directives
1431 @table @code
1432 @item %p
1433 @c supports %-X.Yp
1434 File's name (not the absolute path name, but the name of the file as
1435 it was encountered by @code{find} - that is, as a relative path from
1436 one of the starting points).
1437 @item %f
1438 File's name with any leading directories removed (only the last
1439 element).
1440 @c supports %-X.Yf
1441 @item %h
1442 Leading directories of file's name (all but the last element and the
1443 slash before it).  If the file's name contains no slashes (for example
1444 because it was named on the command line and is in the current working
1445 directory), then ``%h'' expands to ``.''.  This prevents ``%h/%f''
1446 expanding to ``/foo'', which would be surprising and probably not
1447 desirable.
1448 @c supports %-X.Yh
1449 @item %P
1450 File's name with the name of the command line argument under which
1451 it was found removed from the beginning.
1452 @c supports %-X.YP
1453 @item %H
1454 Command line argument under which file was found.
1455 @c supports %-X.YH
1456 @end table
1458 @node Ownership Directives
1459 @subsubsection Ownership Directives
1461 @table @code
1462 @item %g
1463 @c supports %-X.Yg
1464 File's group name, or numeric group ID if the group has no name.
1465 @item %G
1466 @c supports %-X.Yg
1467 @c TODO: Needs to support # flag and 0 flag
1468 File's numeric group ID.
1469 @item %u
1470 @c supports %-X.Yu
1471 File's user name, or numeric user ID if the user has no name.
1472 @item %U
1473 @c supports %-X.Yu
1474 @c TODO: Needs to support # flag
1475 File's numeric user ID.
1476 @item %m
1477 @c full support, including # and 0.
1478 File's permissions (in octal).  If you always want to have a leading
1479 zero on the number, use the '#' format flag, for example '%#m'.
1480 @end table
1482 @node Size Directives
1483 @subsubsection Size Directives
1485 @table @code
1486 @item %k
1487 The amount of disk space used for this file in 1K blocks. Since disk
1488 space is allocated in multiples of the filesystem block size this is
1489 usually greater than %s/1024, but it can also be smaller if the file
1490 is a sparse file (that is, it has ``holes'').
1491 @item %b
1492 The amount of disk space used for this file in 512-byte blocks. Since
1493 disk space is allocated in multiples of the filesystem block size this
1494 is usually greater than %s/1024, but it can also be smaller if the
1495 file is a sparse file (that is, it has ``holes'').
1496 @item %s
1497 File's size in bytes.
1498 @end table
1500 @node Location Directives
1501 @subsubsection Location Directives
1503 @table @code
1504 @item %d
1505 File's depth in the directory tree (depth below a file named on the
1506 command line, not depth below the root directory).  Files named on the
1507 command line have a depth of 0.  Subdirectories immediately below them
1508 have a depth of 1, and so on.
1509 @item %D
1510 The device number on which the file exists (the @code{st_dev} field of
1511 @code{struct stat}), in decimal.
1512 @item %F
1513 Type of the filesystem the file is on; this value can be used for
1514 @samp{-fstype} (@pxref{Directories}).
1515 @item %l
1516 Object of symbolic link (empty string if file is not a symbolic link).
1517 @item %i
1518 File's inode number (in decimal).
1519 @item %n
1520 Number of hard links to file.
1521 @item %y
1522 Type of the file as used with @samp{-type}.  If the file is a symbolic
1523 link, @samp{l} will be printed.
1524 @item %Y
1525 Type of the file as used with @samp{-type}.  If the file is a symbolic
1526 link, it is dereferenced.  If the file is a broken symbolic link,
1527 @samp{N} is printed.
1529 @end table
1531 @node Time Directives
1532 @subsubsection Time Directives
1534 Some of these directives use the C @code{ctime} function.  Its output
1535 depends on the current locale, but it typically looks like
1537 @example
1538 Wed Nov  2 00:42:36 1994
1539 @end example
1541 @table @code
1542 @item %a
1543 File's last access time in the format returned by the C @code{ctime}
1544 function.
1545 @item %A@var{k}
1546 File's last access time in the format specified by @var{k}
1547 (@pxref{Time Formats}).
1548 @item %c
1549 File's last status change time in the format returned by the C
1550 @code{ctime} function.
1551 @item %C@var{k}
1552 File's last status change time in the format specified by @var{k}
1553 (@pxref{Time Formats}).
1554 @item %t
1555 File's last modification time in the format returned by the C
1556 @code{ctime} function.
1557 @item %T@var{k}
1558 File's last modification time in the format specified by @var{k}
1559 (@pxref{Time Formats}).
1560 @end table
1562 @node Time Formats
1563 @subsection Time Formats
1565 Below are the formats for the directives @samp{%A}, @samp{%C}, and
1566 @samp{%T}, which print the file's timestamps.  Some of these formats
1567 might not be available on all systems, due to differences in the C
1568 @code{strftime} function between systems.
1570 @menu
1571 * Time Components::
1572 * Date Components::
1573 * Combined Time Formats::
1574 @end menu
1576 @node Time Components
1577 @subsubsection Time Components
1579 The following format directives print single components of the time.
1581 @table @code
1582 @item H
1583 hour (00..23)
1584 @item I
1585 hour (01..12)
1586 @item k
1587 hour ( 0..23)
1588 @item l
1589 hour ( 1..12)
1590 @item p
1591 locale's AM or PM
1592 @item Z
1593 time zone (e.g., EDT), or nothing if no time zone is determinable
1594 @item M
1595 minute (00..59)
1596 @item S
1597 second (00..61)
1598 @item @@
1599 seconds since Jan. 1, 1970, 00:00 GMT.
1600 @end table
1602 @node Date Components
1603 @subsubsection Date Components
1605 The following format directives print single components of the date.
1607 @table @code
1608 @item a
1609 locale's abbreviated weekday name (Sun..Sat)
1610 @item A
1611 locale's full weekday name, variable length (Sunday..Saturday)
1612 @item b
1613 @itemx h
1614 locale's abbreviated month name (Jan..Dec)
1615 @item B
1616 locale's full month name, variable length (January..December)
1617 @item m
1618 month (01..12)
1619 @item d
1620 day of month (01..31)
1621 @item w
1622 day of week (0..6)
1623 @item j
1624 day of year (001..366)
1625 @item U
1626 week number of year with Sunday as first day of week (00..53)
1627 @item W
1628 week number of year with Monday as first day of week (00..53)
1629 @item Y
1630 year (1970@dots{})
1631 @item y
1632 last two digits of year (00..99)
1633 @end table
1635 @node Combined Time Formats
1636 @subsubsection Combined Time Formats
1638 The following format directives print combinations of time and date
1639 components.
1641 @table @code
1642 @item r
1643 time, 12-hour (hh:mm:ss [AP]M)
1644 @item T
1645 time, 24-hour (hh:mm:ss)
1646 @item X
1647 locale's time representation (H:M:S)
1648 @item c
1649 locale's date and time (Sat Nov 04 12:02:33 EST 1989)
1650 @item D
1651 date (mm/dd/yy)
1652 @item x
1653 locale's date representation (mm/dd/yy)
1654 @item +
1655 Date and time, separated by '+', for example `2004-04-28+22:22:05'.
1656 The time is given in the current timezone (which may be affected by
1657 setting the TZ environment variable).  This is a GNU extension.
1658 @end table
1660 @node Formatting Flags
1661 @subsubsection Formatting Flags
1663 The @samp{%m} and @samp{%d} directives support the @samp{#}, @samp{0}
1664 and @samp{+} flags, but the other directives do not, even if they
1665 print numbers.  Numeric directives that do not support these flags
1666 include
1668 @samp{G},
1669 @samp{U},
1670 @samp{b},
1671 @samp{D},
1672 @samp{k} and
1673 @samp{n}.
1675 All fields support the format flag @samp{-}, which makes fields
1676 left-aligned.  That is, if the field width is greater than the actual
1677 contents of the field, the requisite number of spaces are printed
1678 after the field content instead of before it.
1680 @node Run Commands
1681 @section Run Commands
1683 You can use the list of file names created by @code{find} or
1684 @code{locate} as arguments to other commands.  In this way you can
1685 perform arbitrary actions on the files.
1687 @menu
1688 * Single File::
1689 * Multiple Files::
1690 * Querying::
1691 @end menu
1693 @node Single File
1694 @subsection Single File
1696 Here is how to run a command on one file at a time.
1698 @deffn Action -execdir command ;
1699 Execute @var{command}; true if zero status is returned.  @code{find}
1700 takes all arguments after @samp{-exec} to be part of the command until
1701 an argument consisting of @samp{;} is reached.  It replaces the string
1702 @samp{@{@}} by the current file name being processed everywhere it
1703 occurs in the command.  Both of these constructions need to be escaped
1704 (with a @samp{\}) or quoted to protect them from expansion by the
1705 shell.  The command is executed in the directory in which @code{find}
1706 was run.
1708 For example, to compare each C header file in the current directory
1709 with the file @file{/tmp/master}:
1711 @example
1712 find . -name '*.h' -execdir diff -u '@{@}' /tmp/master ';'
1713 @end example
1714 @end deffn
1717 Another similar option, @samp{-exec} is supported, but is less secure.
1718 @xref{Security Considerations}, for a discussion of the security
1719 problems surrounding @samp{-exec}.
1722 @deffn Action -exec command ;
1723 This insecure variant of the @samp{-execdir} action is specified by
1724 POSIX.  The main difference is that the command is executed in the
1725 directory from which @code{find} was invoked, meaning that @samp{@{@}}
1726 is expanded to a relative path starting with the name of one of the
1727 starting directories, rather than just the basename of the matched
1728 file.
1729 @end deffn
1732 @node Multiple Files
1733 @subsection Multiple Files
1735 Sometimes you need to process files one of the time.  But usually this
1736 is not necessary, and, it is faster to run a command on as many files
1737 as possible at a time, rather than once per file.  Doing this saves on
1738 the time it takes to start up the command each time.
1740 The @samp{-execdir} and @samp{-exec} actions have variants that build
1741 command lines containing as many matched files as possible.
1743 @deffn Action -execdir command @{@} +
1744 This works as for @samp{-execdir command ;}, except that the
1745 @samp{@{@}} at the end of the command is expanded to a list of names
1746 of matching files.  This expansion is done in such a way as to avoid
1747 exceeding the maximum command line length available on the system.
1748 Only one @samp{@{@}} is allowed within the command, and it must appear
1749 at the end, immediately before the @samp{+}.  A @samp{+} appearing in
1750 any position other than immediately after @samp{@{@}} is not
1751 considered to be special (that is, it does not terminate the command).
1752 @end deffn
1755 @deffn Action -exec command @{@} +
1756 This insecure variant of the @samp{-execdir} action is specified by
1757 POSIX.  The main difference is that the command is executed in the
1758 directory from which @code{find} was invoked, meaning that @samp{@{@}}
1759 is expanded to a relative path starting with the name of one of the
1760 starting directories, rather than just the basename of the matched
1761 file.
1762 @end deffn
1764 Before @code{find} exits, any partially-built command lines are
1765 executed.  This happens even if the exit was caused by the
1766 @samp{-quit} action.  However, some types of error (for example not
1767 being able to invoke @code{stat()} on the current directory) can cause
1768 an immediate fatal exit.  In this situation, any partially-built
1769 command lines will not be invoked (this prevents possible infinite
1770 loops).
1772 Another, but less secure, way to run a command on more than one file
1773 at once, is to use the @code{xargs} command, which is invoked like
1774 this:
1776 @example
1777 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
1778 @end example
1780 @code{xargs} normally reads arguments from the standard input.  These
1781 arguments are delimited by blanks (which can be protected with double
1782 or single quotes or a backslash) or newlines.  It executes the
1783 @var{command} (default is @file{/bin/echo}) one or more times with any
1784 @var{initial-arguments} followed by arguments read from standard
1785 input.  Blank lines on the standard input are ignored.
1787 Instead of blank-delimited names, it is safer to use @samp{find
1788 -print0} or @samp{find -fprint0} and process the output by giving the
1789 @samp{-0} or @samp{--null} option to GNU @code{xargs}, GNU @code{tar},
1790 GNU @code{cpio}, or @code{perl}.  The @code{locate} command also has a
1791 @samp{-0} or @samp{--null} option which does the same thing.
1793 You can use shell command substitution (backquotes) to process a list
1794 of arguments, like this:
1796 @example
1797 grep -l sprintf `find $HOME -name '*.c' -print`
1798 @end example
1800 However, that method produces an error if the length of the @samp{.c}
1801 file names exceeds the operating system's command line length limit.
1802 @code{xargs} avoids that problem by running the command as many times
1803 as necessary without exceeding the limit:
1805 @example
1806 find $HOME -name '*.c' -print | xargs grep -l sprintf
1807 @end example
1809 However, if the command needs to have its standard input be a terminal
1810 (@code{less}, for example), you have to use the shell command
1811 substitution method or use the @samp{--arg-file} option of
1812 @code{xargs}.
1814 The @code{xargs} command will process all its input, building command
1815 lines and executing them, unless one of the commands exits with a
1816 status of 255 (this will cause xargs to issue an error message and
1817 stop) or it reads a line contains the end of file string specified
1818 with the @samp{--eof} option.
1820 @menu
1821 * Unsafe File Name Handling::
1822 * Safe File Name Handling::
1823 * Unusual Characters in File Names::
1824 * Limiting Command Size::
1825 * Interspersing File Names::
1826 @end menu
1828 @node Unsafe File Name Handling
1829 @subsubsection Unsafe File Name Handling
1831 Because file names can contain quotes, backslashes, blank characters,
1832 and even newlines, it is not safe to process them using @code{xargs}
1833 in its default mode of operation.  But since most files' names do not
1834 contain blanks, this problem occurs only infrequently.  If you are
1835 only searching through files that you know have safe names, then you
1836 need not be concerned about it.
1838 @c This example is adapted from:
1839 @c From: pfalstad@stone.Princeton.EDU (Paul John Falstad)
1840 @c Newsgroups: comp.unix.shell
1841 @c Subject: Re: Beware xargs security holes
1842 @c Date: 16 Oct 90 19:12:06 GMT
1844 In many applications, if @code{xargs} botches processing a file
1845 because its name contains special characters, some data might be lost.
1846 The importance of this problem depends on the importance of the data
1847 and whether anyone notices the loss soon enough to correct it.
1848 However, here is an extreme example of the problems that using
1849 blank-delimited names can cause.  If the following command is run
1850 daily from @code{cron}, then any user can remove any file on the
1851 system:
1853 @example
1854 find / -name '#*' -atime +7 -print | xargs rm
1855 @end example
1857 For example, you could do something like this:
1859 @example
1860 eg$ echo > '#
1861 vmunix'
1862 @end example
1864 @noindent
1865 and then @code{cron} would delete @file{/vmunix}, if it ran
1866 @code{xargs} with @file{/} as its current directory.
1868 To delete other files, for example @file{/u/joeuser/.plan}, you could
1869 do this:
1871 @example
1872 eg$ mkdir '#
1874 eg$ cd '#
1876 eg$ mkdir u u/joeuser u/joeuser/.plan'
1878 eg$ echo > u/joeuser/.plan'
1879 /#foo'
1880 eg$ cd ..
1881 eg$ find . -name '#*' -print | xargs echo
1882 ./# ./# /u/joeuser/.plan /#foo
1883 @end example
1885 @node Safe File Name Handling
1886 @subsubsection Safe File Name Handling
1888 Here is how to make @code{find} output file names so that they can be
1889 used by other programs without being mangled or misinterpreted.  You
1890 can process file names generated this way by giving the @samp{-0} or
1891 @samp{--null} option to GNU @code{xargs}, GNU @code{tar}, GNU
1892 @code{cpio}, or @code{perl}.
1894 @deffn Action -print0
1895 True; print the entire file name on the standard output, followed by a
1896 null character.
1897 @end deffn
1899 @deffn Action -fprint0 file
1900 True; like @samp{-print0} but write to @var{file} like @samp{-fprint}
1901 (@pxref{Print File Name}).
1902 @end deffn
1904 As of findutils version 4.2.4, the @code{locate} program also has a
1905 @samp{--null} option which does the same thing.  For similarity with
1906 @code{xargs}, the short form of the option @samp{-0} can also be used.
1908 If you want to be able to handle file names safely but need to run
1909 commands which want to be connected to a terminal on their input, you
1910 can use the @samp{--arg-file} option to @code{xargs} like this:
1912 @example
1913 find / -name xyzzy -print0 > list
1914 xargs --null --arg-file=list munge
1915 @end example
1917 The example above runs the @code{munge} program on all the files named
1918 @file{xyzzy} that we can find, but @code{munge}'s input will still be
1919 the terminal (or whatever the shell was using as standard input).  If
1920 your shell has the ``process substitution'' feature @samp{<(...)}, you
1921 can do this in just one step:
1923 @example
1924 xargs --null --arg-file=<(find / -name xyzzy -print0) munge
1925 @end example
1927 @node Unusual Characters in File Names
1928 @subsubsection Unusual Characters in File Names
1929 As discussed above, you often need to be careful about how the names
1930 of files are handled by @code{find} and other programs.  If the output
1931 of @code{find} is not going to another program but instead is being
1932 shown on a terminal, this can still be a problem.  For example, some
1933 character sequences can reprogram the function keys on some terminals.
1934 @xref{Security Considerations}, for a discussion of other security
1935 problems relating to @code{find}.
1937 Unusual characters are handled differently by various
1938 actions, as described below.
1940 @table @samp
1941 @item -print0
1942 @itemx -fprint0
1943 Always print the exact file name, unchanged, even if the output is
1944 going to a terminal.
1945 @item -ok
1946 @itemx -okdir
1947 Always print the exact file name, unchanged.  This will probably
1948 change in a future release.
1949 @item -ls
1950 @itemx -fls
1951 Unusual characters are always escaped.  White space, backslash, and
1952 double quote characters are printed using C-style escaping (for
1953 example @samp{\f}, @samp{\"}).  Other unusual characters are printed
1954 using an octal escape.  Other Printable characters (for @samp{-ls} and
1955 @samp{-fls} these are the characters between octal 041 and 0176) are
1956 printed as-is.
1957 @item -printf
1958 @itemx -fprintf
1959 If the output is not going to a terminal, it is printed as-is.
1960 Otherwise, the result depends on which directive is in use:
1962 @table @asis
1963 @item %D, %F, %H, %Y, %y
1964 These expand to values which are not under control of files' ownwers,
1965 and so are printed as-is.
1966 @item  %a, %b, %c, %d, %g, %G, %i, %k, %m, %M, %n, %s, %t, %u, %U
1967 These have values which are under the control of files' ownwers but
1968 which cannot be used to send arbitrary data to the terminal, and so
1969 these are printed as-is.
1970 @item %f, %h, %l, %p, %P
1971 The output of these directives is quoted if the output is going to a
1972 terminal.
1974 This quoting is performed in the same way as for GNU @code{ls}.  This
1975 is not the same quoting mechanism as the one used for @samp{-ls} and
1976 @samp{fls}.  If you are able to decide what format to use for the
1977 output of @code{find} then it is normally better to use @samp{\0} as a
1978 terminator than to use newline, as file names can contain white space
1979 and newline characters.
1980 @end table
1981 @item -print
1982 @itemx -fprint
1983 Quoting is handled in the same way as for the @samp{%p} directive of
1984 @samp{-printf} and @samp{-fprintf}.  If you are using @code{find} in a
1985 script or in a situation where the matched files might have arbitrary
1986 names, you should consider using @samp{-print0} instead of
1987 @samp{-print}.
1988 @end table
1991 The @code{locate} program quotes and escapes unusual characters in
1992 file names in the same way as @code{find}'s @samp{-print} action.
1994 The behaviours described above may change soon, as the treatment of
1995 unprintable characters is harmonised for @samp{-ls}, @samp{-fls},
1996 @samp{-print}, @samp{-fprint}, @samp{-printf} and @samp{-fprintf}.
1998 @node Limiting Command Size
1999 @subsubsection Limiting Command Size
2001 @code{xargs} gives you control over how many arguments it passes to
2002 the command each time it executes it.  By default, it uses up to
2003 @code{ARG_MAX} - 2k, or 128k, whichever is smaller, characters per
2004 command.  It uses as many lines and arguments as fit within that
2005 limit.  The following options modify those values.
2007 @table @code
2008 @item --no-run-if-empty
2009 @itemx -r
2010 If the standard input does not contain any nonblanks, do not run the
2011 command.  By default, the command is run once even if there is no
2012 input.
2014 @item --max-lines@r{[}=@var{max-lines}@r{]}
2015 @itemx -L@r{[}@var{max-lines}@r{]}
2016 @itemx -l@r{[}@var{max-lines}@r{]}
2017 Use at most @var{max-lines} nonblank input lines per command line;
2018 @var{max-lines} defaults to 1 if omitted.  Trailing blanks cause an
2019 input line to be logically continued on the next input line, for the
2020 purpose of counting the lines.  Implies @samp{-x}.  The preferred
2021 name for this option is @samp{-L} as this is specified by POSIX.  This
2022 option should be compatible with @samp{-I} but currently it is not.
2024 @item --max-args=@var{max-args}
2025 @itemx -n @var{max-args}
2026 Use at most @var{max-args} arguments per command line.  Fewer than
2027 @var{max-args} arguments will be used if the size (see the @samp{-s}
2028 option) is exceeded, unless the @samp{-x} option is given, in which
2029 case @code{xargs} will exit.
2031 @item --max-chars=@var{max-chars}
2032 @itemx -s @var{max-chars}
2033 Use at most @var{max-chars} characters per command line, including the
2034 command initial arguments and the terminating nulls at the ends of
2035 the argument strings.  If you specify a value for this option which is
2036 too large or small, a warning message is printed and the appropriate
2037 upper or lower limit is used instead.
2039 @item --max-procs=@var{max-procs}
2040 @itemx -P @var{max-procs}
2041 Run up to @var{max-procs} processes at a time; the default is 1.  If
2042 @var{max-procs} is 0, @code{xargs} will run as many processes as
2043 possible at a time.  Use the @samp{-n}, @samp{-s}, or @samp{-L} option
2044 with @samp{-P}; otherwise chances are that the command will be run
2045 only once.
2046 @end table
2048 @node Interspersing File Names
2049 @subsubsection Interspersing File Names
2051 @code{xargs} can insert the name of the file it is processing between
2052 arguments you give for the command.  Unless you also give options to
2053 limit the command size (@pxref{Limiting Command Size}), this mode of
2054 operation is equivalent to @samp{find -exec} (@pxref{Single File}).
2056 @table @code
2057 @item --replace@r{[}=@var{replace-str}@r{]}
2058 @itemx -I@r{[}@var{replace-str}@r{]}
2059 @itemx -i@r{[}@var{replace-str}@r{]}
2060 Replace occurrences of @var{replace-str} in the initial arguments with
2061 names read from the input.  Also, unquoted blanks do not
2062 terminate arguments; instead, the input is split at newlines only.  If
2063 @var{replace-str} is omitted, it defaults to @samp{@{@}} (like for
2064 @samp{find -exec}).  Implies @samp{-x} and @samp{-l 1}.  @samp{-i} is
2065 depreceated in favour of @samp{-I}. As an
2066 example, to sort each file in the @file{bills} directory, leaving the
2067 output in that file name with @file{.sorted} appended, you could do:
2069 @example
2070 find bills -type f | xargs -IXX sort -o XX.sorted XX
2071 @end example
2073 @noindent
2074 The equivalent command using @samp{find -execdir} is:
2076 @example
2077 find bills -type f -execdir sort -o '@{@}.sorted' '@{@}' ';'
2078 @end example
2079 @end table
2081 @node Querying
2082 @subsection Querying
2084 To ask the user whether to execute a command on a single file, you can
2085 use the @code{find} primary @samp{-okdir} instead of @samp{-execdir},
2086 and the @code{find} primary @samp{-ok} instead of @samp{-exec}:
2088 @deffn Action -okdir command ;
2089 Like @samp{-execdir} (@pxref{Single File}), but ask the user first (on
2090 the standard input); if the response does not start with @samp{y} or
2091 @samp{Y}, do not run the command, and return false.  If the command is
2092 run, its standard input is redirected from @file{/dev/null}.
2093 @end deffn
2095 @deffn Action -ok command ;
2096 This insecure variant of the @samp{-okdir} action is specified by
2097 POSIX.  The main difference is that the command is executed in the
2098 directory from which @code{find} was invoked, meaning that @samp{@{@}}
2099 is expanded to a relative path starting with the name of one of the
2100 starting directories, rather than just the basename of the matched
2101 file.  If the command is run, its standard input is redirected from
2102 @file{/dev/null}.
2103 @end deffn
2105 When processing multiple files with a single command, to query the
2106 user you give @code{xargs} the following option.  When using this
2107 option, you might find it useful to control the number of files
2108 processed per invocation of the command (@pxref{Limiting Command
2109 Size}).
2111 @table @code
2112 @item --interactive
2113 @itemx -p
2114 Prompt the user about whether to run each command line and read a line
2115 from the terminal.  Only run the command line if the response starts
2116 with @samp{y} or @samp{Y}.  Implies @samp{-t}.
2117 @end table
2119 @node Delete Files
2120 @section Delete Files
2122 @deffn Action -delete
2123 Delete files or directories; true if removal succeeded.  If the
2124 removal failed, an error message is issued.
2126 The use of the @samp{-delete} action on the command line automatically
2127 turns on the @samp{-depth} option (@pxref{find Expressions}).
2128 @end deffn
2130 @node Adding Tests
2131 @section Adding Tests
2133 You can test for file attributes that none of the @code{find} builtin
2134 tests check.  To do this, use @code{xargs} to run a program that
2135 filters a list of files printed by @code{find}.  If possible, use
2136 @code{find} builtin tests to pare down the list, so the program run by
2137 @code{xargs} has less work to do.  The tests builtin to @code{find}
2138 will likely run faster than tests that other programs perform.
2140 For reasons of efficiency it is often useful to limit the number of
2141 times an external program has to be run.  For this reason, it is often
2142 a good idea to implement ``extended'' tests by using @code{xargs}.
2144 For example, here is a way to print the names of all of the unstripped
2145 binaries in the @file{/usr/local} directory tree.  Builtin tests avoid
2146 running @code{file} on files that are not regular files or are not
2147 executable.
2149 @example
2150 find /usr/local -type f -perm /a=x | xargs file |
2151   grep 'not stripped' | cut -d: -f1
2152 @end example
2154 @noindent
2155 The @code{cut} program removes everything after the file name from the
2156 output of @code{file}.
2158 However, using @code{xargs} can present important security problems
2159 (@pxref{Security Considerations}).  These can be avoided by using
2160 @samp{-execdir}.  The @samp{-execdir} action is also a useful way of
2161 putting your own test in the middle of a set of other tests or actions
2162 for @code{find} (for example, you might want to use @samp{-prune}).
2164 @c Idea from Martin Weitzel.
2165 To place a special test somewhere in the middle of a @code{find}
2166 expression, you can use @samp{-execdir} (or, less securely,
2167 @samp{-exec}) to run a program that performs the test.  Because
2168 @samp{-execdir} evaluates to the exit status of the executed program,
2169 you can use a program (which can be a shell script) that tests for a
2170 special attribute and make it exit with a true (zero) or false
2171 (non-zero) status.  It is a good idea to place such a special test
2172 @emph{after} the builtin tests, because it starts a new process which
2173 could be avoided if a builtin test evaluates to false.
2175 Here is a shell script called @code{unstripped} that checks whether
2176 its argument is an unstripped binary file:
2178 @example
2179 #! /bin/sh
2180 file "$1" | grep -q "not stripped"
2181 @end example
2184 This script relies on the shell exiting with the status of
2185 the last command in the pipeline, in this case @code{grep}.  The
2186 @code{grep} command exits with a true status if it found any matches,
2187 false if not.  Here is an example of using the script (assuming it is
2188 in your search path).  It lists the stripped executables (and shell
2189 scripts) in the file @file{sbins} and the unstripped ones in
2190 @file{ubins}.
2192 @example
2193 find /usr/local -type f -perm /a=x \
2194   \( -execdir unstripped '@{@}' \; -fprint ubins -o -fprint sbins \)
2195 @end example
2198 @node Databases, File Permissions, Actions, Top
2199 @chapter File Name Databases
2201 The file name databases used by @code{locate} contain lists of files
2202 that were in particular directory trees when the databases were last
2203 updated.  The file name of the default database is determined when
2204 @code{locate} and @code{updatedb} are configured and installed.  The
2205 frequency with which the databases are updated and the directories for
2206 which they contain entries depend on how often @code{updatedb} is run,
2207 and with which arguments.
2209 You can obtain some statistics about the databases by using
2210 @samp{locate --statistics}.
2212 @menu
2213 * Database Locations::
2214 * Database Formats::
2215 * Newline Handling::
2216 @end menu
2219 @node Database Locations
2220 @section Database Locations
2222 There can be multiple file name databases.  Users can select which
2223 databases @code{locate} searches using the @code{LOCATE_PATH}
2224 environment variable or a command line option.  The system
2225 administrator can choose the file name of the default database, the
2226 frequency with which the databases are updated, and the directories
2227 for which they contain entries.  File name databases are updated by
2228 running the @code{updatedb} program, typically nightly.
2230 In networked environments, it often makes sense to build a database at
2231 the root of each filesystem, containing the entries for that
2232 filesystem.  @code{updatedb} is then run for each filesystem on the
2233 fileserver where that filesystem is on a local disk, to prevent
2234 thrashing the network.
2236 @xref{Invoking updatedb},
2237 for the description of the options to @code{updatedb}, which specify
2238 which directories would each database contain entries for.
2241 @node Database Formats
2242 @section Database Formats
2244 The file name databases contain lists of files that were in particular
2245 directory trees when the databases were last updated.  The file name
2246 database format changed starting with GNU @code{locate} version 4.0 to
2247 allow machines with different byte orderings to share the databases.
2248 The new GNU @code{locate} can read both the old and new database
2249 formats.  However, old versions of @code{locate} and @code{find}
2250 produce incorrect results if given a new-format database.
2252 If you run @samp{locate --statistics}, the resulting summary indicates
2253 the type of each @code{locate} database.
2256 @menu
2257 * New Database Format::
2258 * Sample Database::
2259 * Old Database Format::
2260 @end menu
2262 @node New Database Format
2263 @subsection New Database Format
2265 @code{updatedb} runs a program called @code{frcode} to
2266 @dfn{front-compress} the list of file names, which reduces the
2267 database size by a factor of 4 to 5.  Front-compression (also known as
2268 incremental encoding) works as follows.
2270 The database entries are a sorted list (case-insensitively, for users'
2271 convenience).  Since the list is sorted, each entry is likely to share
2272 a prefix (initial string) with the previous entry.  Each database
2273 entry begins with an offset-differential count byte, which is the
2274 additional number of characters of prefix of the preceding entry to
2275 use beyond the number that the preceding entry is using of its
2276 predecessor.  (The counts can be negative.)  Following the count is a
2277 null-terminated ASCII remainder---the part of the name that follows
2278 the shared prefix.
2280 If the offset-differential count is larger than can be stored in a
2281 byte (+/-127), the byte has the value 0x80 and the count follows in a
2282 2-byte word, with the high byte first (network byte order).
2284 Every database begins with a dummy entry for a file called
2285 @file{LOCATE02}, which @code{locate} checks for to ensure that the
2286 database file has the correct format; it ignores the entry in doing
2287 the search.
2289 Databases cannot be concatenated together, even if the first (dummy)
2290 entry is trimmed from all but the first database.  This is because the
2291 offset-differential count in the first entry of the second and
2292 following databases will be wrong.
2294 In the output of @samp{locate --statistics}, the new database format
2295 is referred to as @samp{LOCATE02}.
2297 @node Sample Database
2298 @subsection Sample Database
2300 Sample input to @code{frcode}:
2301 @c with nulls changed to newlines:
2303 @example
2304 /usr/src
2305 /usr/src/cmd/aardvark.c
2306 /usr/src/cmd/armadillo.c
2307 /usr/tmp/zoo
2308 @end example
2310 Length of the longest prefix of the preceding entry to share:
2312 @example
2313 0 /usr/src
2314 8 /cmd/aardvark.c
2315 14 rmadillo.c
2316 5 tmp/zoo
2317 @end example
2319 Output from @code{frcode}, with trailing nulls changed to newlines
2320 and count bytes made printable:
2322 @example
2323 0 LOCATE02
2324 0 /usr/src
2325 8 /cmd/aardvark.c
2326 6 rmadillo.c
2327 -9 tmp/zoo
2328 @end example
2330 (6 = 14 - 8, and -9 = 5 - 14)
2332 @node Old Database Format
2333 @subsection Old Database Format
2335 The old database format is used by Unix @code{locate} and @code{find}
2336 programs and earlier releases of the GNU ones.  @code{updatedb}
2337 produces this format if given the @samp{--old-format} option.
2339 @code{updatedb} runs programs called @code{bigram} and @code{code} to
2340 produce old-format databases.  The old format differs from the new one
2341 in the following ways.  Instead of each entry starting with an
2342 offset-differential count byte and ending with a null, byte values
2343 from 0 through 28 indicate offset-differential counts from -14 through
2344 14.  The byte value indicating that a long offset-differential count
2345 follows is 0x1e (30), not 0x80.  The long counts are stored in host
2346 byte order, which is not necessarily network byte order, and host
2347 integer word size, which is usually 4 bytes.  They also represent a
2348 count 14 less than their value.  The database lines have no
2349 termination byte; the start of the next line is indicated by its first
2350 byte having a value <= 30.
2352 In addition, instead of starting with a dummy entry, the old database
2353 format starts with a 256 byte table containing the 128 most common
2354 bigrams in the file list.  A bigram is a pair of adjacent bytes.
2355 Bytes in the database that have the high bit set are indexes (with the
2356 high bit cleared) into the bigram table.  The bigram and
2357 offset-differential count coding makes these databases 20-25% smaller
2358 than the new format, but makes them not 8-bit clean.  Any byte in a
2359 file name that is in the ranges used for the special codes is replaced
2360 in the database by a question mark, which not coincidentally is the
2361 shell wildcard to match a single character.
2363 The old format therefore cannot faithfully store entries with
2364 non-ASCII characters. It therefore should not be used in
2365 internationalized environments.
2367 The output of @samp{locate --statistics} will give an incorrect count
2368 of the number of file names containing newlines or high-bit characters
2369 for old-format databases.
2371 @node Newline Handling
2372 @section Newline Handling
2374 Within the database, file names are terminated with a null character.
2375 This is the case for both the old and the new format.
2377 When the new database format is being used, the compression technique
2378 used to generate the database though relies on the ability to sort the
2379 list of files before they are presented to @code{frcode}.
2381 If the system's sort command allows its input list of files to be
2382 separated with null characters via the @samp{-z} option, this option
2383 is used and therefore @code{updatedb} and @code{locate} will both
2384 correctly handle file names containing newlines.  If the @code{sort}
2385 command lacks support for this, the list of files is delimited with
2386 the newline character, meaning that parts of file names containing
2387 newlines will be incorrectly sorted.  This can result in both
2388 incorrect matches and incorrect failures to match.
2390 On the other hand, if you are using the old database format, file
2391 names with embedded newlines are not correctly handled.  There is no
2392 technical limitation which enforces this, it's just that the
2393 @code{bigram} program has not been updated to support lists of file
2394 names separated by nulls.
2396 So, if you are using the new database format (this is the default) and
2397 your system uses GNU @code{sort}, newlines will be correctly handled
2398 at all times.  Otherwise, newlines may not be correctly handled.
2400 @node File Permissions, Reference, Databases, Top
2401 @chapter File Permissions
2403 @include perm.texi
2405 @node Reference, Common Tasks, File Permissions, Top
2406 @chapter Reference
2408 Below are summaries of the command line syntax for the programs
2409 discussed in this manual.
2411 @menu
2412 * Invoking find::
2413 * Invoking locate::
2414 * Invoking updatedb::
2415 * Invoking xargs::
2416 * Regular Expressions::
2417 @end menu
2419 @node Invoking find, Invoking locate, , Reference
2420 @section Invoking @code{find}
2422 @example
2423 find @r{[-H] [-L] [-P]} @r{[}@var{file}@dots{}@r{]} @r{[}@var{expression}@r{]}
2424 @end example
2426 @code{find} searches the directory tree rooted at each file name
2427 @var{file} by evaluating the @var{expression} on each file it finds in
2428 the tree.
2430 The options @samp{-H}, @samp{-L} or @samp{-P} may be specified at the
2431 start of the command line (if none of these is specified, @samp{-P} is
2432 assumed).  The arguments after these are a list of files or
2433 directories that should be searched.
2435 This list of files to search is followed by a list of expressions
2436 describing the files we wish to search for.  The first part of the
2437 expression is recognised by the fact that it begins with @samp{-},
2438 @samp{(}, @samp{)}, @samp{,}, or @samp{!}.  Any arguments after it are
2439 the rest of the expression.  If no files are given, the current
2440 directory is used.  If no expression is given, the expression
2441 @samp{-print} is used.
2443 @code{find} exits with status zero if all files matched are processed
2444 successfully, greater than 0 if errors occur.
2446 Three options can precede the list of files.  They determine the
2447 way that symbolic links are handled.
2449 @table @code
2450 @item -P
2451 Never follow symbolic links (this is the default), except in the case
2452 of the @samp{-xtype} predicate.
2453 @item -L
2454 Always follow symbolic links, except in the case of the @samp{-xtype}
2455 predicate.
2456 @item -H
2457 Follow symbolic links specified in the list of files to search, or
2458 which are otherwise specified on the command line.
2459 @end table
2461 If @code{find} would follow a symbolic link, but cannot for any reason
2462 (for example, because it has insufficient permissions or the link is
2463 broken), it falls back on using the properties of the symbolic link
2464 itself.  @ref{Symbolic Links} for a more complete description of how
2465 symbolic links are handled.
2467 @xref{Primary Index}, for a summary of all of the tests, actions, and
2468 options that the expression can contain.  If the expression is
2469 missing, @samp{-print} is assumed.
2472 @code{find} also recognizes two options for administrative use:
2474 @table @code
2475 @item --help
2476 Print a summary of the command line usage and exit.
2477 @item --version
2478 Print the version number of @code{find} and exit.
2479 @end table
2482 @menu
2483 * Warning Messages::
2484 @end menu
2487 @node Warning Messages,,, Invoking find
2488 @subsection Warning Messages
2490 If there is an error on the @code{find} command line, an error message
2491 is normally issued.  However, there are some usages that are
2492 inadvisable but which @code{find} should still accept.  Under these
2493 circumstances, @code{find} may issue a warning message.  By default,
2494 warnings are enabled only if @code{find} is being run interactively
2495 (specifically, if the standard input is a terminal).  Warning messages
2496 can be controlled explicitly by the use of options on the command
2497 line:
2499 @table @code
2500 @item -warn
2501 Issue warning messages where appropriate.
2502 @item -nowarn
2503 Do not issue warning messages.
2504 @end table
2506 These options take effect at the point on the command line where they
2507 are specified.  Therefore if you specify @samp{-nowarn} at the end of
2508 the command line, you will not see warning messages for any problems
2509 occurring before that.  The warning messages affected by the above
2510 options are triggered by:
2512 @itemize @minus
2513 @item
2514 Use of the @samp{-d} option which is deprecated; please use
2515 @samp{-depth} instead, since the latter is POSIX-compliant.
2516 @item
2517 Use of the @samp{-ipath} option which is deprecated; please use
2518 @samp{-iwholename} instead.
2519 @item
2520 Specifying an option (for example @samp{-mindepth}) after a non-option
2521 (for example @samp{-type} or @samp{-print}) on the command line.
2522 @end itemize
2525 The default behaviour above is designed to work in that way so that
2526 existing shell scripts which use such constructs don't generate
2527 spurious errors, but people will be made aware of the problem.
2529 Some warning messages are issued for less common or more serious
2530 problems, and consequently cannot be turned off:
2532 @itemize @minus
2533 @item
2534 Use of an unrecognised backslash escape sequence with @samp{-fprintf}
2535 @item
2536 Use of an unrecognised formatting directive with @samp{-fprintf}
2537 @end itemize
2539 @node Invoking locate, Invoking updatedb, Invoking find, Reference
2540 @section Invoking @code{locate}
2542 @example
2543 locate @r{[}@var{option}@dots{}@r{]} @var{pattern}@dots{}
2544 @end example
2546 For each @var{pattern} given @code{locate} searches one or more file
2547 name databases returning each match of @var{pattern}.
2549 For each @var{pattern} given @code{locate} searches one or more file
2550 name databases returning each match of @var{pattern}.
2552 @table @code
2553 @item --all
2554 @itemx -A
2555 Print only names which match all non-option arguments, not those
2556 matching one or more non-option arguments.
2558 @item --basename
2559 @itemx -b
2560 The specified pattern is matched against just the last component of
2561 the name of a file in the @code{locate} database.  This last
2562 component is also called the ``base name''.  For example, the base
2563 name of @file{/tmp/mystuff/foo.old.c} is @file{foo.old.c}.  If the
2564 pattern contains metacharacters, it must match the base name exactly.
2565 If not, it must match part of the base name.
2567 @item --count
2568 @itemx -c
2569 Instead of printing the matched file names, just print the total
2570 number of matches found, unless @samp{--print} (@samp{-p}) is also
2571 present.
2574 @item --database=@var{path}
2575 @itemx -d @var{path}
2576 Instead of searching the default @code{locate} database, @code{locate} search the file
2577 name databases in @var{path}, which is a colon-separated list of
2578 database file names.  You can also use the environment variable
2579 @code{LOCATE_PATH} to set the list of database files to search.  The
2580 option overrides the environment variable if both are used.  Empty
2581 elements in @var{path} (that is, a leading or trailing colon, or two
2582 colons in a row) are taken to stand for the default database.
2583 A database can be supplied on stdin, using @samp{-} as an element
2584 of @samp{path}. If more than one element of @samp{path} is @samp{-},
2585 later instances are ignored (but a warning message is printed).
2587 @item --existing
2588 @itemx -e
2589 Only print out such names which currently exist (instead of such names
2590 which existed when the database was created).  Note that this may slow
2591 down the program a lot, if there are many matches in the database.
2592 The way in which broken symbolic links are treated is affected by the
2593 @samp{-L}, @samp{-P} and @samp{-H} options.
2595 @item --non-existing
2596 @itemx -E
2597 Only print out such names which currently do not exist (instead of
2598 such names which existed when the database was created).  Note that
2599 this may slow down the program a lot, if there are many matches in the
2600 database.  The way in which broken symbolic links are treated is
2601 affected by the @samp{-L}, @samp{-P} and @samp{-H} options.
2603 @item --follow
2604 @itemx -L
2605 If testing for the existence of files (with the @samp{-e} or @samp{-E}
2606 options), consider broken symbolic links to be non-existing.  This is
2607 the default behaviour.
2610 @item --nofollow
2611 @itemx -P
2612 @itemx -H
2613 If testing for the existence of files (with the @samp{-e} or @samp{-E}
2614 options), treat broken symbolic links as if they were existing files.
2615 The @samp{-H} form of this option is provided purely for similarity
2616 with @code{find}; the use of @samp{-P} is recommended over @samp{-H}.
2618 @item --ignore-case
2619 @itemx -i
2620 Ignore case distinctions in both the pattern and the file names.
2622 @item --limit=N
2623 @itemx -l N
2624 Limit the number of results printed to N.  When used with the
2625 @samp{--count} option, the value printed will never be larger than
2626 this limit.
2628 @item --mmap
2629 @itemx -m
2630 Accepted but does nothing.  The option is supported only to provide
2631 compatibility with BSD's @code{locate}.
2633 @item --null
2634 @itemx -0
2635 Results are separated with the ASCII NUL character rather than the
2636 newline character.  To get the full benefit of the use of this option,
2637 use the new @code{locate} database format (that is the default
2638 anyway).
2640 @item --print
2641 @itemx -p
2642 Print search results when they normally would not, because of the
2643 presence of @samp{--statistics} (@samp{-S}) or @samp{--count}
2644 (@samp{-c}).
2646 @item --wholename
2647 @itemx -w
2648 The specified pattern is matched against the whole name of the file in
2649 the @code{locate} database.  If the pattern contains metacharacters,
2650 it must match exactly.  If not, it must match part of the whole file
2651 name.  This is the default behaviour.
2653 @item --regex
2654 @itemx -r
2655 Instead of using substring or shell glob matching, the pattern
2656 specified on the command line is understood to be a regular
2657 expression.  GNU Emacs-style regular expressions are assumed unless
2658 the @samp{--regextype} option is also given.  File names from the
2659 @code{locate} database are matched using the specified regular
2660 expression.  If the @samp{-i} flag is also given, matching is
2661 case-insensitive.  Matches are performed against the whole path name,
2662 and so by default a pathname will be matched if any part of it matches
2663 the specified regular expression.  The regular expression may use
2664 @samp{^} or @samp{$} to anchor a match at the beginning or end of a
2665 pathname.
2667 @item --regextype
2668 This option changes the regular expression dialect used.  Dialects
2669 understood are described in @ref{Regular Expressions}.
2673 @item --regextype
2674 This option changes the regular expression syntax and behaviour used
2675 by the @samp{--regex} option.  @ref{Regular Expressions} for more
2676 information on the regular expression dialects understood by GNU
2677 findutils.
2679 @item --stdio
2680 @itemx -s
2681 Accepted but does nothing.  The option is supported only to provide
2682 compatibility with BSD's @code{locate}.
2684 @item --statistics
2685 @itemx -S
2686 Print some summary information for each @code{locate} database.  No
2687 search is performed unless non-option arguments are given.
2689 @item --help
2690 Print a summary of the command line usage for @code{locate} and exit.
2692 @item --version
2693 Print the version number of @code{locate} and exit.
2694 @end table
2696 @node Invoking updatedb, Invoking xargs, Invoking locate, Reference
2697 @section Invoking @code{updatedb}
2699 @example
2700 updatedb @r{[}@var{option}@dots{}@r{]}
2701 @end example
2703 @code{updatedb} creates and updates the database of file names used by
2704 @code{locate}.  @code{updatedb} generates a list of files similar to
2705 the output of @code{find} and then uses utilities for optimizing the
2706 database for performance.  @code{updatedb} is often run periodically
2707 as a @code{cron} job and configured with environment variables or
2708 command options.  Typically, operating systems have a shell script
2709 that ``exports'' configurations for variable definitions and uses
2710 another schell script that ``sources'' the configuration file into the
2711 environment and then executes @code{updatedb} in the environment.
2713 @code{updatedb} creates and updates the database of file names used by
2714 @code{locate}.  @code{updatedb} generates a list of files similar to
2715 the output of @code{find} and then uses utilities for optimizing the
2716 database for performance.  @code{updatedb} is often run periodically
2717 as a @code{cron} job and configured with environment variables or
2718 command options.  Typically, operating systems have a shell script
2719 that ``exports'' configurations for variable definitions and uses
2720 another schell script that ``sources'' the configuration file into the
2721 environment and then executes @code{updatedb} in the environment.
2723 @table @code
2724 @item --findoptions='@var{OPTION}@dots{}'
2725 Global options to pass on to @code{find}.
2726 The environment variable @code{FINDOPTIONS} also sets this value.
2727 Default is none.
2729 @item --localpaths='@var{path}@dots{}'
2730 Non-network directories to put in the database.
2731 Default is @file{/}.
2733 @item --netpaths='@var{path}@dots{}'
2734 Network (NFS, AFS, RFS, etc.) directories to put in the database.
2735 The environment variable @code{NETPATHS} also sets this value.
2736 Default is none.
2738 @item --prunepaths='@var{path}@dots{}'
2739 Directories to omit from the database, which would otherwise be
2740 included.  The environment variable @code{PRUNEPATHS} also sets this
2741 value.  Default is @file{/tmp /usr/tmp /var/tmp /afs}.  The paths are
2742 used as regular expressions (with @code{find ... -regex}, so you need
2743 to specify these paths in the same way that @code{find} will encounter
2744 them.  This means for example that the paths must not include trailing
2745 slashes.
2747 @item --prunefs='@var{path}@dots{}'
2748 Filesystems to omit from the database, which would otherwise be
2749 included.  Note that files are pruned when a filesystem is reached;
2750 Any filesystem mounted under an undesired filesystem will be ignored.
2751 The environment variable @code{PRUNEFS} also sets this value.  Default
2752 is @file{nfs NFS proc}.
2754 @item --output=@var{dbfile}
2755 The database file to build.  Default is system-dependent, but
2756 typically @file{/usr/local/var/locatedb}.
2758 @item --localuser=@var{user}
2759 The user to search the non-network directories as, using @code{su}.
2760 Default is to search the non-network directories as the current user.
2761 You can also use the environment variable @code{LOCALUSER} to set this user.
2763 @item --netuser=@var{user}
2764 The user to search network directories as, using @code{su}.  Default
2765 @code{user} is @code{daemon}.  You can also use the environment variable
2766 @code{NETUSER} to set this user.
2768 @item --old-format
2769 Generate a @code{locate} database in the old format, for compatibility
2770 with versions of @code{locate} other than GNU @code{locate}.  Using
2771 this option means that @code{locate} will not be able to properly
2772 handle non-ASCII characters in file names (that is, file names
2773 containing characters which have the eighth bit set, such as many of
2774 the characters from the ISO-8859-1 character set).
2775 @item --help
2776 Print a summary of the command line usage and exit.
2777 @item --version
2778 Print the version number of @code{updatedb} and exit.
2779 @end table
2781 @node Invoking xargs, Regular Expressions,  Invoking updatedb, Reference
2782 @section Invoking @code{xargs}
2784 @example
2785 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
2786 @end example
2788 @code{xargs} exits with the following status:
2790 @table @asis
2791 @item 0
2792 if it succeeds
2793 @item 123
2794 if any invocation of the command exited with status 1-125
2795 @item 124
2796 if the command exited with status 255
2797 @item 125
2798 if the command is killed by a signal
2799 @item 126
2800 if the command cannot be run
2801 @item 127
2802 if the command is not found
2803 @item 1
2804 if some other error occurred.
2805 @end table
2807 @table @code
2808 @item --arg-file@r{=@var{inputfile}}
2809 @itemx -a o@r{@var{inputfile}}
2810 Read names from the file @var{inputfile} instead of standard input.
2812 @item --null
2813 @itemx -0
2814 Input file names are terminated by a null character instead of by
2815 whitespace, and any quotes and backslash characters are not considered special (every
2816 character is taken literally).  Disables the end of file string, which
2817 is treated like any other argument.
2819 @item --eof@r{[}=@var{eof-str}@r{]}
2820 @itemx -e@r{[}@var{eof-str}@r{]}
2821 Set the end of file string to @var{eof-str}.  If the end of file
2822 string occurs as a line of input, the rest of the input is ignored.
2823 If @var{eof-str} is omitted, there is no end of file string.  If this
2824 option is not given, the end of file string defaults to @samp{_}.
2826 @item --help
2827 Print a summary of the options to @code{xargs} and exit.
2829 @item --replace@r{[}=@var{replace-str}@r{]}
2830 @itemx -I@r{[}@var{replace-str}@r{]}
2831 @itemx -i@r{[}@var{replace-str}@r{]}
2832 Replace occurrences of @var{replace-str} in the initial arguments with
2833 names read from standard input.  Also, unquoted blanks do not
2834 terminate arguments; instead, the input is split at newlines only.
2835 If @var{replace-str} is omitted, it defaults to @samp{@{@}}
2836 (like for @samp{find -exec}).  Implies @samp{-x} and @samp{-l 1}.  @samp{-i} is
2837 depreceated in favour of @samp{-I}.
2839 @item --max-lines@r{[}=@var{max-lines}@r{]}
2840 @itemx -l@r{[}@var{max-lines}@r{]}
2841 Use at most @var{max-lines} non-blank input lines per command line;
2842 @var{max-lines} defaults to 1 if omitted.  Trailing blanks cause an
2843 input line to be logically continued on the next input line, for the
2844 purpose of counting the lines.  Implies @samp{-x}.
2846 @item --max-args=@var{max-args}
2847 @itemx -n @var{max-args}
2848 Use at most @var{max-args} arguments per command line.  Fewer than
2849 @var{max-args} arguments will be used if the size (see the @samp{-s}
2850 option) is exceeded, unless the @samp{-x} option is given, in which
2851 case @code{xargs} will exit.
2853 @item --interactive
2854 @itemx -p
2855 Prompt the user about whether to run each command line and read a line
2856 from the terminal.  Only run the command line if the response starts
2857 with @samp{y} or @samp{Y}.  Implies @samp{-t}.
2859 @item --no-run-if-empty
2860 @itemx -r
2861 If the standard input is completely empty, do not run the
2862 command.  By default, the command is run once even if there is no
2863 input.
2865 @item --max-chars=@var{max-chars}
2866 @itemx -s @var{max-chars}
2867 Use at most @var{max-chars} characters per command line, including the
2868 command, initial arguments and any terminating nulls at the ends of
2869 the argument strings.
2871 @item --verbose
2872 @itemx -t
2873 Print the command line on the standard error output before executing
2876 @item --version
2877 Print the version number of @code{xargs} and exit.
2879 @item --exit
2880 @itemx -x
2881 Exit if the size (see the @samp{-s} option) is exceeded.
2884 @item --max-procs=@var{max-procs}
2885 @itemx -P @var{max-procs}
2886 Run simultaneously up to @var{max-procs} processes at once; the default is 1.  If
2887 @var{max-procs} is 0, @code{xargs} will run as many processes as
2888 possible simultaneously.
2889 @end table
2892 @node Regular Expressions,, Invoking xargs, Reference
2893 @section Regular Expressions
2895 The @samp{-regex} and @samp{-iregex} tests of @code{find} allow
2896 matching by regular expression, as does the @samp{--regex} option of
2897 @code{locate}.  There are many different types of Regular Expression,
2898 but the type used by @code{find} and @code{locate} is the same as is
2899 used in GNU Emacs.  Both programs provide an option which allows you
2900 to select an alternative regular expression syntax; for @code{find}
2901 this is the @samp{-regextype} option, and for @code{locate} this is
2902 the @samp{--regextype} option.
2904 These options take a single argument, which indicates the specific
2905 regular expression syntax and behaviour that should be used.  This
2906 should be one of the following:
2908 @include regexprops.texi
2911 @node Common Tasks, Worked Examples, Reference, Top
2912 @chapter Common Tasks
2914 The sections that follow contain some extended examples that both give
2915 a good idea of the power of these programs, and show you how to solve
2916 common real-world problems.
2918 @menu
2919 * Viewing And Editing::
2920 * Archiving::
2921 * Cleaning Up::
2922 * Strange File Names::
2923 * Fixing Permissions::
2924 * Classifying Files::
2925 @end menu
2927 @node Viewing And Editing
2928 @section Viewing And Editing
2930 To view a list of files that meet certain criteria, simply run your
2931 file viewing program with the file names as arguments.  Shells
2932 substitute a command enclosed in backquotes with its output, so the
2933 whole command looks like this:
2935 @example
2936 less `find /usr/include -name '*.h' | xargs grep -l mode_t`
2937 @end example
2939 @noindent
2940 You can edit those files by giving an editor name instead of a file
2941 viewing program:
2943 @example
2944 emacs `find /usr/include -name '*.h' | xargs grep -l mode_t`
2945 @end example
2947 Because there is a limit to the length of any individual command line,
2948 there is a limit to the number of files that can be handled in this
2949 way.  We can get around this difficulty by using xargs like this:
2951 @example
2952 find /usr/include -name '*.h' | xargs grep -l mode_t > todo
2953 xargs --arg-file=todo emacs
2954 @end example
2956 Here, @code{xargs} will run @code{emacs} as many times as necessary to
2957 visit all of the files listed in the file @file{todo}.
2959 @node Archiving
2960 @section Archiving
2962 You can pass a list of files produced by @code{find} to a file
2963 archiving program.  GNU @code{tar} and @code{cpio} can both read lists
2964 of file names from the standard input---either delimited by nulls (the
2965 safe way) or by blanks (the lazy, risky default way).  To use
2966 null-delimited names, give them the @samp{--null} option.  You can
2967 store a file archive in a file, write it on a tape, or send it over a
2968 network to extract on another machine.
2970 One common use of @code{find} to archive files is to send a list of
2971 the files in a directory tree to @code{cpio}.  Use @samp{-depth} so if
2972 a directory does not have write permission for its owner, its contents
2973 can still be restored from the archive since the directory's
2974 permissions are restored after its contents.  Here is an example of
2975 doing this using @code{cpio}; you could use a more complex @code{find}
2976 expression to archive only certain files.
2978 @example
2979 find . -depth -print0 |
2980   cpio --create --null --format=crc --file=/dev/nrst0
2981 @end example
2983 You could restore that archive using this command:
2985 @example
2986 cpio --extract --null --make-dir --unconditional \
2987   --preserve --file=/dev/nrst0
2988 @end example
2990 Here are the commands to do the same things using @code{tar}:
2992 @example
2993 find . -depth -print0 |
2994   tar --create --null --files-from=- --file=/dev/nrst0
2996 tar --extract --null --preserve-perm --same-owner \
2997   --file=/dev/nrst0
2998 @end example
3000 @c Idea from Rick Sladkey.
3001 Here is an example of copying a directory from one machine to another:
3003 @example
3004 find . -depth -print0 | cpio -0o -Hnewc |
3005   rsh @var{other-machine} "cd `pwd` && cpio -i0dum"
3006 @end example
3008 @node Cleaning Up
3009 @section Cleaning Up
3011 @c Idea from Jim Meyering.
3012 This section gives examples of removing unwanted files in various
3013 situations.  Here is a command to remove the CVS backup files created
3014 when an update requires a merge:
3016 @example
3017 find . -name '.#*' -print0 | xargs -0r rm -f
3018 @end example
3020 The command above works, but the following is safer:
3022 @example
3023 find . -name '.#*' -depth -delete
3024 @end example
3026 @c Idea from Franc,ois Pinard.
3027 You can run this command to clean out your clutter in @file{/tmp}.
3028 You might place it in the file your shell runs when you log out
3029 (@file{.bash_logout}, @file{.logout}, or @file{.zlogout}, depending on
3030 which shell you use).
3032 @example
3033 find /tmp -depth -user "$LOGNAME" -type f -delete
3034 @end example
3036 If your @code{find} command removes directories, you may find that
3037 you get a spurious error message when @code{find} tries to recurse
3038 into a directory that has now been removed.  Using the @samp{-depth}
3039 option will normally resolve this problem.
3041 @c Idea from Noah Friedman.
3042 To remove old Emacs backup and auto-save files, you can use a command
3043 like the following.  It is especially important in this case to use
3044 null-terminated file names because Emacs packages like the VM mailer
3045 often create temporary file names with spaces in them, like
3046 @file{#reply to David J. MacKenzie<1>#}.
3048 @example
3049 find ~ \( -name '*~' -o -name '#*#' \) -print0 |
3050   xargs --no-run-if-empty --null rm -vf
3051 @end example
3053 Removing old files from @file{/tmp} is commonly done from @code{cron}:
3055 @c Idea from Kaveh Ghazi.
3056 @example
3057 find /tmp /var/tmp -not -type d -mtime +3 -delete
3058 find /tmp /var/tmp -depth -mindepth 1 -type d -empty -delete
3059 @end example
3061 The second @code{find} command above uses @samp{-depth} so it cleans
3062 out empty directories depth-first, hoping that the parents become
3063 empty and can be removed too.  It uses @samp{-mindepth} to avoid
3064 removing @file{/tmp} itself if it becomes totally empty.
3066 @node Strange File Names
3067 @section Strange File Names
3069 @c Idea from:
3070 @c From: tmatimar@isgtec.com (Ted Timar)
3071 @c Newsgroups: comp.unix.questions,comp.unix.shell,comp.answers,news.answers
3072 @c Subject: Unix - Frequently Asked Questions (2/7) [Frequent posting]
3073 @c Subject: How do I remove a file with funny characters in the filename ?
3074 @c Date: Thu Mar 18 17:16:55 EST 1993
3075 @code{find} can help you remove or rename a file with strange
3076 characters in its name.  People are sometimes stymied by files whose
3077 names contain characters such as spaces, tabs, control characters, or
3078 characters with the high bit set.  The simplest way to remove such
3079 files is:
3081 @example
3082 rm -i @var{some*pattern*that*matches*the*problem*file}
3083 @end example
3085 @code{rm} asks you whether to remove each file matching the given
3086 pattern.  If you are using an old shell, this approach might not work
3087 if the file name contains a character with the high bit set; the shell
3088 may strip it off.  A more reliable way is:
3090 @example
3091 find . -maxdepth 1 @var{tests} -okdir rm '@{@}' \;
3092 @end example
3094 @noindent
3095 where @var{tests} uniquely identify the file.  The @samp{-maxdepth 1}
3096 option prevents @code{find} from wasting time searching for the file
3097 in any subdirectories; if there are no subdirectories, you may omit
3098 it.  A good way to uniquely identify the problem file is to figure out
3099 its inode number; use
3101 @example
3102 ls -i
3103 @end example
3105 Suppose you have a file whose name contains control characters, and
3106 you have found that its inode number is 12345.  This command prompts
3107 you for whether to remove it:
3109 @example
3110 find . -maxdepth 1 -inum 12345 -okdir rm -f '@{@}' \;
3111 @end example
3113 If you don't want to be asked, perhaps because the file name may
3114 contain a strange character sequence that will mess up your screen
3115 when printed, then use @samp{-execdir} instead of @samp{-okdir}.
3117 If you want to rename the file instead, you can use @code{mv} instead
3118 of @code{rm}:
3120 @example
3121 find . -maxdepth 1 -inum 12345 -okdir mv '@{@}' @var{new-file-name} \;
3122 @end example
3124 @node Fixing Permissions
3125 @section Fixing Permissions
3127 Suppose you want to make sure that everyone can write to the
3128 directories in a certain directory tree.  Here is a way to find
3129 directories lacking either user or group write permission (or both),
3130 and fix their permissions:
3132 @example
3133 find . -type d -not -perm -ug=w | xargs chmod ug+w
3134 @end example
3136 @noindent
3137 You could also reverse the operations, if you want to make sure that
3138 directories do @emph{not} have world write permission.
3140 @node Classifying Files
3141 @section Classifying Files
3143 @c Idea from:
3144 @c From: martin@mwtech.UUCP (Martin Weitzel)
3145 @c Newsgroups: comp.unix.wizards,comp.unix.questions
3146 @c Subject: Advanced usage of 'find' (Re: Unix security automating script)
3147 @c Date: 22 Mar 90 15:05:19 GMT
3148 If you want to classify a set of files into several groups based on
3149 different criteria, you can use the comma operator to perform multiple
3150 independent tests on the files.  Here is an example:
3152 @example
3153 find / -type d \( -perm -o=w -fprint allwrite , \
3154   -perm -o=x -fprint allexec \)
3156 echo "Directories that can be written to by everyone:"
3157 cat allwrite
3158 echo ""
3159 echo "Directories with search permissions for everyone:"
3160 cat allexec
3161 @end example
3163 @code{find} has only to make one scan through the directory tree
3164 (which is one of the most time consuming parts of its work).
3166 @node Worked Examples, Security Considerations, Common Tasks, Top
3167 @chapter Worked Examples
3169 The tools in the findutils package, and in particular @code{find},
3170 have a large number of options.  This means that quite often,
3171 there is more than one way to do things.  Some of the options
3172 and facilities only exist for compatibility with other tools, and
3173 findutils provides improved ways of doing things.
3175 This chapter describes a number of useful tasks that are commonly
3176 performed, and compares the different ways of achieving them.
3178 @menu
3179 * Deleting Files::
3180 * Updating A Timestamp File::
3181 @end menu
3183 @node Deleting Files
3184 @section Deleting Files
3186 One of the most common tasks that @code{find} is used for is locating
3187 files that can be deleted.  This might include:
3189 @itemize
3190 @item 
3191 Files last modified more than 3 years ago which haven't been accessed
3192 for at least 2 years
3193 @item
3194 Files belonging to a certain user
3195 @item
3196 Temporary files which are no longer required
3197 @end itemize
3199 This example concentrates on the actual deletion task rather than on
3200 sophisticated ways of locatng the files that need to be deleted.
3201 We'll assume that the files we want to delete are old files underneath
3202 @file{/var/tmp/stuff}.
3204 @subsection The Traditional Way
3206 The traditional way to delete files in @file{var/tmp/stuff} that have
3207 not been modified in over 90 days would have been:
3209 @smallexample
3210 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \;
3211 @end smallexample
3213 The above command uses @samp{-exec} to run the @code{/bin/rm} command
3214 to remove each file.  This approach works and in fact would have
3215 worked in Version 7 Unix in 1979.  However, there are a number of
3216 problems with this approach.
3219 The most obvious problem with the approach above is that it causes
3220 @code{find} to fork every time it finds a file that needs to delete,
3221 and the child process then has to use the @code{exec} system call to
3222 launch @code{/bin/rm}.   All this is quite inefficient.  If we are
3223 going to use @code{/bin/rm} to do this job, it is better to make it
3224 delete more than one file at a time.  
3226 The most obvious way of doing this is to use the shell's command
3227 expansion feature:
3229 @smallexample
3230 /bin/rm `find /var/tmp/stuff -mtime +90 -print`
3231 @end smallexample
3232 or you could use the more modern form
3233 @smallexample
3234 /bin/rm $(find /var/tmp/stuff -mtime +90 -print)
3235 @end smallexample
3237 The commands above are much more efficient than the first attempt.
3238 However, there is a problem with them.  The shell has a maximum
3239 command length which is imposed by the operating system (the actual
3240 limit varies between systems).  This means that while the command
3241 expansion technique will usually work, it will suddenly fail when
3242 there are lots of files to delete.  Since the task is to delete
3243 unwanted files, this is precisely the time we don't want things to go
3244 wrong.
3246 @subsection Making Use of xargs
3248 So, is there a way to be more efficient in the use of @code{fork()}
3249 and @code{exec()} without running up against this limit?
3250 Yes, we can be almost optimally efficient by making use
3251 of the @code{xargs} command.  The @code{xargs} command reads arguments
3252 from its standard input and builds them into command lines.  We can
3253 use it like this:
3255 @smallexample
3256 find /var/tmp/stuff -mtime +90 -print | xargs /bin/rm 
3257 @end smallexample
3259 For example if the files found by @code{find} are
3260 @file{/var/tmp/stuff/A}, 
3261 @file{/var/tmp/stuff/B} and 
3262 @file{/var/tmp/stuff/C} then @code{xargs} might issue the commands 
3264 @smallexample
3265 /bin/rm /var/tmp/stuff/A /var/tmp/stuff/B
3266 /bin/rm /var/tmp/stuff/C
3267 @end smallexample
3269 The above assumes that @code{xargs} has a very small maximum command
3270 line length.  The real limit is much larger but the idea is that
3271 @code{xargs} will run @code{/bin/rm} as many times as necessary to get
3272 the job done, given the limits on command line length.
3274 This usage of @code{xargs} is pretty efficient, and the @code{xargs}
3275 command is widely implemented (all modern versions of Unix offer it).
3276 So far then, the news is all good.  However, there is bad news too.
3278 @subsection Unusual characters in filenames
3280 Unix-like systems allow any characters to appear in file names with
3281 the exception of the ASCII NUL character and the backslash.
3282 Backslashes can occur in path names (as the directory separator) but
3283 not in the names of actual directory entries.  This means that the
3284 list of files that @code{xargs} reads could in fact contain white space
3285 characters --- spaces, tabs and newline characters.  Since by default,
3286 @code{xargs} assumes that the list of files it is reading uses white
3287 space as an argument separator, it cannot correctly handle the case
3288 where a filename actually includes white space.  This makes the
3289 default behaviour of @code{xargs} almost useless for handling
3290 arbitrary data.
3292 To solve this problem, GNU findutils introduced the @samp{-print0}
3293 action for @code{find}.  This uses the ASCII NUL character to separate
3294 the entries in the file list that it produces.  This is the ideal
3295 choice of separator since it is the only character that cannot appear
3296 within a path name.  The @samp{-0} option to @code{xargs} makes it
3297 assume that arguments are separated with ASCII NUL instead of white
3298 space.  It also turns off another misfeature in the default behaviour
3299 of @code{xargs}, which is that it pays attention to quote characters
3300 in its input.  Some versions of @code{xargs} also terminate when they
3301 see a lone @samp{_} in the input, but GNU @code{find} no longer does
3302 that (since it has become an optional behaviour in the Unix standard).
3304 So, putting @code{find -print0} together with @code{xargs -0} we get
3305 this command:
3307 @smallexample
3308 find /var/tmp/stuff -mtime +90 -print0 | xargs -0 /bin/rm 
3309 @end smallexample
3311 The result is an efficient way of proceeding that
3312 correctly handles all the possible characters that could appear in the
3313 list of files to delete.  This is good news.  However, there is, as
3314 I'm sure you're expecting, also more bad news.  The problem is that
3315 this is not a portable construct; although other versions of Unix
3316 (notable BSD-derived ones) support @samp{-print0}, it's not
3317 universal.  So, is there a more universal mechanism?
3319 @subsection Going back to -exec
3321 There is indeed a more universal mechanism, which is a slight
3322 modification to the @samp{-exec} action.  The normal @samp{-exec}
3323 action assumes that the command to run is terminated with a semicolon
3324 (the semicolon normally has to be quoted in order to protect it from
3325 interpretation as the shell command separator).  The SVR4 edition of
3326 Unix introduced a slight variation, which involves terminating the
3327 command with @samp{+} instead:
3329 @smallexample
3330 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \+
3331 @end smallexample
3333 The above use of @samp{-exec} causes @code{find} to build up a long
3334 command line and then issue it.  This can be less efficient than some
3335 uses of @code{xargs}; for example @code{xargs} allows new command
3336 lines to be built up while the previous command is still executing, and
3337 allows you to specify a number of commands to run in parallel.
3338 However, the @code{find @dots{} -exec @dots{} +} construct has the advantage
3339 of wide portability.  GNU findutils did not support @samp{-exec @dots{} +}
3340 until version 4.2.12; one of the reasons for this is that it already
3341 had the @samp{-print0} action in any case.
3344 @subsection A more secure version of -exec
3346 The command above seems to be efficient and portable.  However,
3347 within it lurks a security problem.  The problem is shared with
3348 all the commands we've tried in this worked example so far, too.  The
3349 security problem is a race condition; that is, if it is possible for
3350 somebody to manipulate the filesystem that you are searching while you
3351 are searching it, it is possible for them to persuade your @code{find}
3352 command to cause the deletion of a file that you can delete but they
3353 normally cannot.  
3355 The problem occurs because the @samp{-exec} action is defined by the
3356 @acronym{POSIX} standard to invoke its command with the same working directory
3357 as @code{find} had when it was started.  This means that the arguments
3358 which replace the @{@} include a relative path from @code{find}'s
3359 starting point down the file that needs to be deleted.  For example,
3361 @smallexample
3362 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \+
3363 @end smallexample
3365 might actually issue the command:
3367 @smallexample
3368 /bin/rm /var/tmp/stuff/A /var/tmp/stuff/B /var/tmp/stuff/passwd
3369 @end smallexample
3371 Notice the file @file{/var/tmp/stuff/passwd}.  Likewise, the command:
3373 @smallexample
3374 cd /var/tmp && find stuff -mtime +90 -exec /bin/rm @{@} \+
3375 @end smallexample
3377 might actually issue the command:
3379 @smallexample
3380 /bin/rm stuff/A stuff/B stuff/passwd
3381 @end smallexample
3383 If an attacker can rename @file{stuff} to something else (making use
3384 of their write permissions in @file{/var/tmp}) they can replace it
3385 with a symbolic link to @file{/etc}.  That means that the
3386 @code{/bin/rm} command will be invoked on @file{/etc/passwd}.  If you
3387 are running your @code{find} command as root, the attacker has just managed
3388 to delete a vital file.  All they needed to do to achieve this was
3389 replace a subdirectory with a symbolic link at the vital moment.
3391 There is however, a simple solution to the problem.  This is an action
3392 which works a lot like @code{-exec} but doesn't need to traverse a
3393 chain of directories to reach the file that it needs to work on.  This
3394 is the @samp{-execdir} action, which was introduced by the BSD family
3395 of operating systems.   The command,
3397 @smallexample
3398 find /var/tmp/stuff -mtime +90 -execdir /bin/rm @{@} \+
3399 @end smallexample
3401 might delete a set of files by performing these actions:
3403 @enumerate
3404 @item 
3405 Change directory to /var/tmp/stuff/foo
3406 @item 
3407 Invoke @code{/bin/rm ./file1 ./file2 ./file3}
3408 @item
3409 Change directory to /var/tmp/stuff/bar
3410 @item 
3411 Invoke @code{/bin/rm ./file99 ./file100 ./file101}
3412 @end enumerate
3414 This is a much more secure method.  We are no longer exposed to a race
3415 condition.  For many typical uses of @code{find}, this is the best
3416 strategy.   It's reasonably efficient, but the length of the command
3417 line is limited not just by the operating system limits, but also by
3418 how many files we actually need to delete from each directory.
3420 Is it possible to do any better?   In the case of general file
3421 processing, no.  However, in the specific case of deleting files it is
3422 indeed possible to do better.  
3424 @subsection Using the -delete action
3426 The most efficient and secure method of solving this problem is to use
3427 the @samp{-delete} action:
3429 @smallexample
3430 find /var/tmp/stuff -mtime +90 -delete
3431 @end smallexample
3433 This alternative is more efficient than any of the @samp{-exec} or
3434 @samp{-execdir} actions, since it entirely avoids the overhead of
3435 forking a new process and using @code{exec} to run @code{/bin/rm}.  It
3436 is also normally more efficient than @code{xargs} for the same
3437 reason.   The file deletion is performed from the directory containing
3438 the entry to be deleted, so the @samp{-delete} action has the same
3439 security advantages as the @samp{-execdir} action has.  
3441 The @samp{-delete} action was introduced by the BSD family of
3442 operating systems.
3444 @subsection Improving things still further
3446 Is it possible to improve things still further?  Not without either
3447 modifying the system library to the operating system or having more specific
3448 knowledge of the layout of the filesystem and disk I/O subsystem, or
3449 both.
3451 The @code{find} command traverses the filesystem, reading
3452 directories.  It then issues a separate system call for each file to
3453 be deleted.  If we could modify the operating system, there are
3454 potential gains that could be made:
3456 @itemize
3457 @item
3458 We could have a system call to which we pass more than one filename
3459 for deletion
3460 @item
3461 Alternatively, we could pass in a list of inode numbers (on GNU/Linux
3462 systems, @code{readdir()} also returns the inode number of each
3463 directory entry) to be deleted.
3464 @end itemize
3466 The above possibilities sound interesting, but from the kernel's point
3467 of view it is difficult to enforce standard Unix access controls for
3468 such processing by inode number.  Such a facility would probably
3469 need to be restricted to the superuser.
3471 Another way of improving performance would be to increase the
3472 parallelism of the process.  For example if the directory hierarchy we
3473 are searching is actually spread across a number of disks, we might
3474 somehow be able to arrange for @code{find} to process each disk in
3475 parallel.  In practice GNU @code{find} doesn't have such an intimate
3476 understanding of the system's filesystem layout and disk I/O
3477 subsystem.
3479 However, since the system administrator can have such an understanding
3480 they can take advantage of it like so:
3482 @smallexample
3483 find /var/tmp/stuff1 -mtime +90 -delete &
3484 find /var/tmp/stuff2 -mtime +90 -delete &
3485 find /var/tmp/stuff3 -mtime +90 -delete &
3486 find /var/tmp/stuff4 -mtime +90 -delete &
3487 wait
3488 @end smallexample
3490 In the example above, four spearate instances of @code{find} are used
3491 to search four subdirectories in parallel.  The @code{wait} command
3492 simply waits for all of these to complete.  Whether this approach is
3493 more or less efficient than a single instance of @code{find} depends
3494 on a number of things:
3496 @itemize
3497 @item
3498 Are the directories being searched in parallel actually on separate
3499 disks?  If not, this parallel search might just result in a lot of
3500 disk head movement and so the speed might even be slower.
3501 @item
3502 Other activity - are other programs also doing things on those disks?
3503 @end itemize
3506 @subsection Conclusion
3508 The fastest and most secure way to delete files with the help of
3509 @code{find} is to use @samp{-delete}.  Using @code{xargs -0 -P N} can
3510 also make effective use of the disk, but it is not as secure.
3512 In the case where we're doing things other than deleting files, the
3513 most secure alternative is @samp{-execdir @dots{} +}, but this is not as
3514 portable as the insecure action @samp{-exec @dots{} +}.
3516 The @samp{-delete} action is not completely portable, but the only
3517 other possiblility which is as secure (@samp{-execdir}) is no more
3518 portable.  The most efficient portable alternative is @samp{-exec
3519 @dots{}+}, but this is insecure and isn't supported by versions of GNU
3520 findutils prior to 4.2.12.
3523 @node Updating A Timestamp File
3524 @section Updating A Timestamp File
3526 Suppose we have a directory full of files which is maintained with a
3527 set of automated tools; perhaps one set of tools updates them and
3528 another set of tools uses the result.  In this situation, it might be
3529 useful for the second set of tools to know if the files have recently
3530 been changed.  It might be useful, for example, to have a 'timestamp'
3531 file which gives the timestamp on the newest file in the collection.
3533 We can use @code{find} to achieve this, but there are several
3534 different ways to do it.
3536 @subsection Updating the Timestamp The Wrong Way
3538 The obvious but wrong answer is just to use @samp{-newer}:-
3540 @smallexample
3541 find subdir -newer timestamp -exec touch -r @{@} timestamp \; 
3542 @end smallexample
3544 This does the right sort of thing but has a bug.  Suppose that two
3545 files in the subdirectory have been updated, and that these are called
3546 @file{file1} and @file{file2}.  The command above will update
3547 @file{timestamp} with the modification time of @file{file1} or that of
3548 @file{file2}, but we don't know which one.  Since the timestamps on
3549 @file{file1} and @file{file2} will in general be different, this could
3550 well be the wrong value.
3552 One solution to this problem is to modify @code{find} to recheck the
3553 modification time of @file{timestamp} every time a file is to be
3554 compared against it, but that will reduce the performence of
3555 @code{find}.
3557 @subsection Using the test utlity to compare timestamps
3559 The @code{test} command can be used to compare timestamps:
3561 @smallexample
3562 find subdir -exec test @{@} -nt timestamp \; -exec touch -r @{@} timestamp \; 
3563 @end smallexample
3565 This will ensure that any changes made to the modification time of
3566 @file{timestamp} that take place during the execution of @code{find}
3567 are taken into account.  This resolves our earlier problem, but
3568 unfortunately this runs much more slowly.
3570 @subsection A combined approach
3572 We can of course still use @samp{-newer} to cut down on the number of
3573 calls to @code{test}:
3575 @smallexample
3576 find subdir -newer timestamp -a \
3577      -exec test @{@} -nt timestamp \; -a \
3578      -exec touch -r @{@} timestamp \; 
3579 @end smallexample
3581 Here, the @samp{-newer} test excludes all he files which are
3582 definitely older than the timestamp, but all the files which are newer
3583 than the old value of the timestamp are compared against the current
3584 updated timestamp.
3586 This is indeed faster in general, but the speed difference will depend
3587 on how many updated files there are.
3589 @subsection Using -printf and sort to compare timestamps
3591 It is possible to use the @samp{-printf} action to abandon the use of
3592 @code{test} entirely:
3594 @smallexample
3595 newest=$(find subdir -newer timestamp -printf "%A@:%p\n" | 
3596            sort -n | 
3597            tail -1 | 
3598            cut -d: -f2- ) 
3599 touch -r "$@{newest:-timestamp@}" timestamp
3600 @end smallexample
3602 The command above works by generating a list of the timestamps and
3603 names of all the files which are newer than the timestamp.  The
3604 @code{sort}, @code{tail} and @code{cut} comands simply pull out the
3605 name of the file with the largest timestamp value (that is, the latest
3606 file).  The @code{touch} command is then used to update the timestamp,
3608 The @code{"$@{newest:-timestamp@}"} expression simply expands to the
3609 value of @code{$newest} if that variable is set, but to
3610 @file{timestamp} otherwise.  This ensures that an argument is always
3611 given to the @samp{-r} option of the @code{touch} command.
3613 This approach seems quite efficient, but unfortunately it has a bug.
3614 Many operating systems now keep file modification time information at
3615 a granularity which is finer than one second.  Unfortunately the
3616 @samp{%A@@} format for @samp{-printf} only prints a whole-number value
3617 currently; that is, these values are at a one-second granularity.
3618 This means that in our example above, @samp{$newest} wil be the name
3619 of a file which is no more than one second older than the newest file,
3620 but may indeed be older.
3622 It would be possible to solve this problem with some kind of loop:
3624 @smallexample
3625 while true; do
3626         newest=$(find subdir -newer timestamp -printf "%A@@:%p\n" | 
3627            sort -n | 
3628            tail -1 | 
3629            cut -d: -f2- ) 
3630         if test -z "$newest" ; then
3631                 break
3632         else
3633                 touch -r "$newest" timestamp
3634         fi
3635 done
3636 @end smallexample
3638 A better fix for this problem would be to allow the @samp{%A@@} format
3639 to produce a result having a fractional part, too.  While this is
3640 planned for GNU @code{find}, it hasn't been done yet.
3642 @subsection Coping with sub-second timestamp resolution
3644 Another tool which often works with timestamps is @code{make}.  We can
3645 use @code{find} to generate a @file{Makefile} file on the fly and then
3646 use @code{make} to update the timestamps:
3648 @smallexample
3649 makefile=$(mktemp)
3650 find subdir \
3651         \( \! -xtype l \) \
3652         -newer timestamp \
3653         -printf "timestamp:: %p\n\ttouch -r %p timestamp\n\n" > "$makefile"
3654 make -f "$makefile"
3655 rm   -f "$makefile"
3656 @end smallexample
3658 Unfortunately although the solution above is quite elegant, it fails
3659 to cope with white space within file names, and adjusting it to do so
3660 would require a rather complex shell script.
3663 @subsection Coping with odd filenames too
3665 We can fix both of these problems (looping and problems with white
3666 space), and do things more efficiently too.  The following command
3667 works with newlines and doesn't need to sort the list of filenames.
3669 @smallexample
3670 find subdir -newer timestamp -printf "%A@@:%p\0" | 
3671    perl -0 newest.pl |
3672    xargs --no-run-if-empty --null -i \
3673       find @{@} -maxdepth 0 -newer timestamp -exec touch -r @{@} timestamp \;
3674 @end smallexample
3676 The first @code{find} command generates a list of files which are
3677 newer than the original timestamp file, and prints a list of them with
3678 their timestamps.  The @file{newest.pl} script simply filters out all
3679 the filenames which have timestamps which are older than whatever the
3680 newest file is:-
3682 @smallexample
3683 @verbatim
3684 #! /usr/bin/perl -0
3685 my @newest = ();
3686 my $latest_stamp = undef;
3687 while (<>) {
3688     my ($stamp, $name) = split(/:/);
3689     if (!defined($latest_stamp) || ($tstamp > $latest_stamp)) {
3690         $latest_stamp = $stamp;
3691         @newest = ();
3692     }
3693     if ($tstamp >= $latest_stamp) {
3694         push @newest, $name;
3695     }
3697 print join("\0", @newest);
3698 @end verbatim
3699 @end smallexample
3701 This prints a list of zero or more files, all of which are newer than
3702 the original timestamp file, and which have the same timestamp as each
3703 other, to the nearest second.  The second @code{find} command takes
3704 each resulting file one at a time, and if that is newer than the
3705 timestamp file, the timestamp is updated.
3707 @node Security Considerations, Error Messages, Worked Examples, Top
3708 @chapter Security Considerations
3710 Security considerations are important if you are using @code{find} or
3711 @code{xargs} to search for or process files that don't belong to you
3712 or which other people have control.  Security considerations
3713 relating to @code{locate} may also apply if you have files which you
3714 do not want others to see.
3716 The most severe forms of security problems affecting
3717 @code{find} and related programs are when third parties bring
3718 about a situation allowing them to do something
3719 they would normally not be able to accomplish.  This is called @emph{privilege
3720 elevation}.  This might include deleting files they would not normally
3721 be able to delete.  It is common for the operating system to periodically
3722 invoke @code{find} for self-maintenance purposes.  These invocations of
3723 @code{find} are particularly problematic from a security point of view
3724 as these are often invoked by the superuser and search the entire
3725 filesystem hierarchy.  Generally, the severity of any associated problem depends
3726 on what the system is going to do with the files found by @code{find}.
3728 @menu
3729 * Levels of Risk::      What is your level of exposure to security problems?
3730 * Security Considerations for find::  Security problems with find
3731 * Security Considerations for xargs:: Security problems with xargs
3732 * Security Considerations for locate:: Security problems with locate
3733 * Security Summary:: That was all very complex, what does it boil down to?
3734 @end menu
3737 @node Levels of Risk
3738 @section Levels of Risk
3740 There are some security risks inherent in the use of @code{find},
3741 @code{xargs} and (to a lesser extent) @code{locate}.  The severity of
3742 these risks depends on what sort of system you are using:
3744 @table @strong
3745 @item High risk
3746 Multi-user systems where you do not control (or trust) the other
3747 users, and on which you execute @code{find}, including areas where
3748 those other users can manipulate the filesystem (for example beneath
3749 @file{/home} or @file{/tmp}).
3751 @item Medium Risk
3752 Systems where the actions of other users can create file names chosen
3753 by them, but to which they don't have access while @code{find} is
3754 being run.  This access might include leaving programs running (shell
3755 background jobs, @code{at} or @code{cron} tasks, for example).  On
3756 these sorts of systems, carefully written commands (avoiding use of
3757 @samp{-print} for example) should not expose you to a high degree of
3758 risk.  Most systems fall into this category.
3760 @item Low Risk
3761 Systems to which untrusted parties do not have access, cannot create
3762 file names of their own choice (even remotely) and which contain no
3763 security flaws which might enable an untrusted third party to gain
3764 access.  Most systems do not fall into this category because there are
3765 many ways in which external parties can affect the names of files that
3766 are created on your system.  The system on which I am writing this for
3767 example automatically downloads software updates from the Internet;
3768 the names of the files in which these updates exist are chosen by
3769 third parties@footnote{Of course, I trust these parties to a large
3770 extent anyway, because I install software provided by them; I choose
3771 to trust them in this way, and that's a deliberate choice}.
3772 @end table
3774 In the discussion above, ``risk'' denotes the likelihood that someone
3775 can cause @code{find}, @code{xargs}, @code{locate} or some other
3776 program which is controlled by them to do something you did not
3777 intend.  The levels of risk suggested do not take any account of the
3778 consequences of this sort of event.  That is, if you operate a ``low
3779 risk'' type system, but the consequences of a security problem are
3780 disastrous, then you should still give serious thought to all the
3781 possible security problems, many of which of course will not be
3782 discussed here -- this section of the manual is intended to be
3783 informative but not comprehensive or exhaustive.
3785 If you are responsible for the operation of a system where the
3786 consequences of a security problem could be very important, you should
3787 do two things:-
3789 @enumerate
3790 @item Define a security policy which defines who is allowed to do what
3791 on your system.
3792 @item Seek competent advice on how to enforce your policy, detect
3793 breaches of that policy, and take account of any potential problems
3794 that might fall outside the scope of your policy.
3795 @end enumerate
3798 @node Security Considerations for find
3799 @section Security Considerations for @code{find}
3802 Some of the actions @code{find} might take have a direct effect;
3803 these include @code{-exec} and @code{-delete}.  However, it is also
3804 common to use @code{-print} explicitly or implicitly, and so if
3805 @code{find} produces the wrong list of file names, that can also be a
3806 security problem; consider the case for example where @code{find} is
3807 producing a list of files to be deleted.
3809 We normally assume that the @code{find} command line expresses the
3810 file selection criteria and actions that the user had in mind -- that
3811 is, the command line is ``trusted'' data.
3813 From a security analysis point of view, the output of @code{find}
3814 should be correct; that is, the output should contain only the names
3815 of those files which meet the user's criteria specified on the command
3816 line.  This applies for the @code{-exec} and @code{-delete} actions;
3817 one can consider these to be part of the output.
3819 On the other hand, the contents of the filesystem can be manipulated
3820 by other people, and hence we regard this as ``untrusted'' data.  This
3821 implies that the @code{find} command line is a filter which converts
3822 the untrusted contents of the filesystem into a correct list of output
3823 files.
3825 The filesystem will in general change while @code{find} is searching
3826 it; in fact, most of the potential security problems with @code{find}
3827 relate to this issue in some way.
3829 @dfn{Race conditions} are a general class of security problem where the
3830 relative ordering of actions taken by @code{find} (for example) and
3831 something else are critically important in getting the correct and expected result@footnote{This is more or less the
3832 definition of the term ``race condition''} .
3834 For @code{find}, an attacker might move or rename files or directories in
3835 the hope that an action might be taken against a file which was not
3836 normally intended to be affected.  Alternatively, this sort of attack
3837 might be intended to persuade @code{find} to search part of the
3838 filesystem which would not normally be included in the search
3839 (defeating the @code{-prune} action for example).
3841 @menu
3842 * Changing the Current Working Directory::
3843 * Race Conditions with -exec::
3844 * Race Conditions with -print and -print0::
3845 @end menu
3848 @node Changing the Current Working Directory
3849 @subsection Changing the Current Working Directory
3851 As @code{find} searches the filesystem, it finds subdirectories and
3852 then searches within them by changing its working directory.  First,
3853 @code{find} reaches and recognizes a subdirectory.  It then decides if that
3854 subdirectory meets the criteria for being searched; that is, any
3855 @samp{-xdev} or @samp{-prune} expressions are taken into account.  The
3856 @code{find} program will then change working directory and proceed to
3857 search the directory.
3859 A race condition attack might take the form that once the checks
3860 relevant to @samp{-xdev} and @samp{-prune} have been done, an attacker
3861 might rename the directory that was being considered, and put in its
3862 place a symbolic link that actually points somewhere else.
3864 The idea behind this attack is to fool @code{find} into going into the
3865 wrong directory.  This would leave @code{find} with a working
3866 directory chosen by an attacker, bypassing any protection apparently
3867 provided by @samp{-xdev} and @samp{-prune}, and any protection
3868 provided by being able to @emph{not} list particular directories on
3869 the @code{find} command line.  This form of attack is particularly
3870 problematic if the attacker can predict when the @code{find} command
3871 will be run, as is the case with @code{cron} tasks for example.
3873 GNU @code{find} has specific safeguards to prevent this general class
3874 of problem.  The exact form of these safeguards depends on the
3875 properties of your system.
3877 @menu
3878 * O_NOFOLLOW::                     Safely changing directory using fchdir().
3879 * Systems without O_NOFOLLOW::     Checking for symbolic links after chdir().
3880 @end menu
3882 @node O_NOFOLLOW
3883 @subsubsection O_NOFOLLOW
3885 If your system supports the O_NOFOLLOW flag @footnote{GNU/Linux
3886 (kernel version 2.1.126 and later) and FreeBSD (3.0-CURRENT and later)
3887 support this} to the @code{open(2)} system call, @code{find} uses it
3888 when safely changing directory.  The target directory is first opened
3889 and then @code{find} changes working directory with the
3890 @code{fchdir()} system call.  This ensures that symbolic links are not
3891 followed, preventing the sort of race condition attack in which use
3892 is made of symbolic links.
3894 If for any reason this approach does not work, @code{find} will fall
3895 back on the method which is normally used if O_NOFOLLOW is not
3896 supported.
3898 You can tell if your system supports O_NOFOLLOW by running
3900 @example
3901 find --version
3902 @end example
3904 This will tell you the version number and which features are enabled.
3905 For example, if I run this on my system now, this gives:
3906 @example
3907 GNU find version 4.2.18-CVS
3908 Features enabled: D_TYPE O_NOFOLLOW(enabled)
3909 @end example
3911 Here, you can see that I am running a version of @code{find} which was
3912 built from the development (CVS) code prior to the release of
3913 findutils-4.2.18, and that the D_TYPE and O_NOFOLLOW features are
3914 present.  O_NOFOLLOW is qualified with ``enabled''.  This simply means
3915 that the current system seems to support O_NOFOLLOW.  This check is
3916 needed because it is possible to build @code{find} on a system that
3917 defines O_NOFOLLOW and then run it on a system that ignores the
3918 O_NOFOLLOW flag.  We try to detect such cases at startup by checking
3919 the operating system and version number; when this happens you will
3920 see ``O_NOFOLLOW(disabled)'' instead.
3922 @node Systems without O_NOFOLLOW
3923 @subsubsection Systems without O_NOFOLLOW
3925 The strategy for preventing this type of problem on systems that lack
3926 support for the O_NOFOLLOW flag is more complex.  Each time
3927 @code{find} changes directory, it examines the directory it is about
3928 to move to, issues the @code{chdir()} system call, and then checks
3929 that it has ended up in the subdirectory it expected.  If all is as
3930 expected, processing continues as normal.  However, there are two main
3931 reasons why the directory might change: the use of an automounter and
3932 the someone removing the old directory and replacing it with something
3933 else while @code{find} is trying to descend into it.
3935 Where a filesystem ``automounter'' is in use it can be the case that
3936 the use of the @code{chdir()} system call can itself cause a new
3937 filesystem to be mounted at that point.  On systems that do not
3938 support O_NOFOLLOW, this will cause @code{find}'s security check to
3939 fail.
3941 However, this does not normally represent a security problem, since
3942 the automounter configuration is normally set up by the system
3943 administrator.  Therefore, if the @code{chdir()} sanity check fails,
3944 @code{find} will make one more attempt.  If that succeeds, execution
3945 carries on as normal.  This is the usual case for automounters.
3947 Where an attacker is trying to exploit a race condition, the problem
3948 may not have gone away on the second attampt.  If this is the case,
3949 @code{find} will issue a warning message and then ignore that
3950 subdirectory.  When this happens, actions such as @samp{-exec} or
3951 @samp{-print} may already have taken place for the problematic
3952 subdirectory.  This is because @code{find} applies tests and actions
3953 to directories before searching within them (unless @samp{-depth} was
3954 specified).
3956 Because of the nature of the directory-change operation and security
3957 check, in the worst case the only things that @code{find} would have
3958 done with the directory are to move into it and back out to the
3959 original parent.  No operations would have been performed within that
3960 directory.
3962 @node Race Conditions with -exec
3963 @subsection Race Conditions with -exec
3965 The @samp{-exec} action causes another program to be run.  It passes
3966 to the program the name of the file which is being considered at the
3967 time.  The invoked program will typically then perform some action
3968 on that file.  Once again, there is a race condition which can be
3969 exploited here.  We shall take as a specific example the command
3971 @example
3972 find /tmp -path /tmp/umsp/passwd -exec /bin/rm
3973 @end example
3975 In this simple example, we are identifying just one file to be deleted
3976 and invoking @code{/bin/rm} to delete it.  A problem exists because
3977 there is a time gap between the point where @code{find} decides that
3978 it needs to process the @samp{-exec} action and the point where the
3979 @code{/bin/rm} command actually issues the @code{unlink()} system
3980 call to delete the file from the filesystem.  Within this time period, an attacker can rename the
3981 @file{/tmp/umsp} directory, replacing it with a symbolic link to
3982 @file{/etc}.  There is no way for @code{/bin/rm} to determine that it
3983 is working on the same file that @code{find} had in mind.  Once the
3984 symbolic link is in place, the attacker has persuaded @code{find} to
3985 cause the deletion of the @file{/etc/passwd} file, which is not the
3986 effect intended by the command which was actually invoked.
3988 One possible defence against this type of attack is to modify the
3989 behaviour of @samp{-exec} so that the @code{/bin/rm} command is run
3990 with the argument @file{./passwd} and a suitable choice of working
3991 directory.  This would allow the normal sanity check that @code{find}
3992 performs to protect against this form of attack too.  Unfortunately,
3993 this strategy cannot be used as the POSIX standard specifies that the
3994 current working directory for commands invoked with @samp{-exec} must
3995 be the same as the current working directory from which @code{find}
3996 was invoked.  This means that the @samp{-exec} action is inherently
3997 insecure and can't be fixed.
3999 GNU @code{find} implements a more secure variant of the @samp{-exec}
4000 action, @samp{-execdir}.  The @samp{-execdir} action
4001 ensures that it is not necessary to dereference subdirectories to
4002 process target files.  The current directory used to invoke programs
4003 is the same as the directory in which the file to be processed exists
4004 (@file{/tmp/umsp} in our example, and only the basename of the file to
4005 be processed is passed to the invoked command, with a @samp{./}
4006 prepended (giving @file{./passwd} in our example).
4008 The @samp{-execdir} action refuses to do anything if the current
4009 directory is included in the @var{$PATH} environment variable.  This
4010 is necessary because @samp{-execdir} runs programs in the same
4011 directory in which it finds files -- in general, such a directory
4012 might be writable by untrusted users.  For similar reasons,
4013 @samp{-execdir} does not allow @samp{@{@}} to appear in the name of
4014 the command to be run.
4016 @node Race Conditions with -print and -print0
4017 @subsection Race Conditions with -print and -print0
4019 The @samp{-print} and @samp{-print0} actions can be used to produce a
4020 list of files matching some criteria, which can then be used with some
4021 other command, perhaps with @code{xargs}.  Unfortunately, this means
4022 that there is an unavoidable time gap between @code{find} deciding
4023 that one or more files meet its criteria and the relevant command
4024 being executed.  For this reason, the @samp{-print} and @samp{-print0}
4025 actions are just as insecure as @samp{-exec}.
4027 In fact, since the construction
4029 @example
4030 find @dots{}  -print | xargs @enddots{}
4031 @end example
4033 does not cope correctly with newlines or other ``white space'' in
4034 file names, and copes poorly with file names containing quotes, the
4035 @samp{-print} action is less secure even than @samp{-print0}.
4038 @comment  node-name,  next,  previous,  up
4039 @comment @node Security Considerations for xargs
4040 @node Security Considerations for xargs
4041 @section Security Considerations for @code{xargs}
4043 The description of the race conditions affecting the @samp{-print}
4044 action of @code{find} shows that @code{xargs} cannot be secure if it
4045 is possible for an attacker to modify a filesystem after @code{find}
4046 has started but before @code{xargs} has completed all its actions.
4048 However, there are other security issues that exist even if it is not
4049 possible for an attacker to have access to the filesystem in real
4050 time.  Firstly, if it is possible for an attacker to create files with
4051 names of their choice on the filesystem, then @code{xargs} is
4052 insecure unless the @samp{-0} option is used.  If a file with the name
4053 @file{/home/someuser/foo/bar\n/etc/passwd} exists (assume that
4054 @samp{\n} stands for a newline character), then @code{find @dots{} -print}
4055 can be persuaded to print three separate lines:
4057 @example
4058 /home/someuser/foo/bar
4060 /etc/passwd
4061 @end example
4063 If it finds a blank line in the input, @code{xargs} will ignore it.
4064 Therefore, if some action is to be taken on the basis of this list of
4065 files, the @file{/etc/passwd} file would be included even if this was
4066 not the intent of the person running find.  There are circumstances in
4067 which an attacker can use this to their advantage.  The same
4068 consideration applies to file names containing ordinary spaces rather
4069 than newlines, except that of course the list of file names will no
4070 longer contain an ``extra'' newline.
4072 This problem is an unavoidable consequence of the default behaviour of
4073 the @code{xargs} command, which is specified by the POSIX standard.
4074 The only ways to avoid this problem are either to avoid all use of
4075 @code{xargs} in favour for example of @samp{find -exec} or (where
4076 available) @samp{find -execdir}, or to use the @samp{-0} option, which
4077 ensures that @code{xargs} considers file names to be separated by
4078 ASCII NUL characters rather than whitespace.  However, useful as this
4079 option is, the POSIX standard does not make it mandatory.
4081 @comment  node-name,  next,  previous,  up
4082 @node Security Considerations for locate
4083 @section Security Considerations for @code{locate}
4085 It is fairly unusual for the output of @code{locate} to be fed into
4086 another command.  However, if this were to be done, this would raise
4087 the same set of security issues as the use of @samp{find @dots{} -print}.
4088 Although the problems relating to whitespace in file names can be
4089 resolved by using @code{locate}'s @samp{-0} option, this still leaves
4090 the race condition problems associated with @samp{find @dots{} -print0}.
4091 There is no way to avoid these problems in the case of @code{locate}.
4093 @node Security Summary
4094 @section Summary
4096 Where untrusted parties can create files on the system, or affect the
4097 names of files that are created, all uses for @code{find},
4098 @code{locate} and @code{xargs} have known security problems except the
4099 following:
4101 @table @asis
4102 @item Informational use only
4103 Uses where the programs are used to prepare lists of file names upon
4104 which no further action will ever be taken.
4106 @item @samp{-delete}
4107 Use of the @samp{-delete} action with @code{find} to delete files
4108 which meet specified criteria
4110 @item @samp{-execdir}
4111 Use of the @samp{-execdir} action with @code{find} where the
4112 @env{PATH} environment variable contains directories which contain
4113 only trusted programs.
4114 @end table
4116 @comment  node-name,  next,  previous,  up
4117 @node Error Messages, Primary Index, Security Considerations, Top
4118 @chapter Error Messages
4120 This section describes some of the error messages sometimes made by
4121 @code{find}, @code{xargs}, or @code{locate}, explains them and in some
4122 cases provides advice as to what you should do about this.
4124 This manual is written in English.  The GNU findutils software
4125 features translations of error messages for many languages.  For this
4126 reason the error messages produced by
4127 the programs are made to be as self-explanatory as possible.  This approach avoids leaving people to
4128 figure out which test an English-language error message
4129 corresponds to. Error messages which are self-explanatory
4130 will not normally be mentioned in this document.  For
4131 those messages mentioned in this document, only the
4132 English-language version of the message will be listed.
4134 @menu
4135 * Error Messages From find::
4136 * Error Messages From xargs::
4137 * Error Messages From locate::
4138 * Error Messages From updatedb::
4139 @end menu
4141 @node Error Messages From find, Error Messages From xargs, , Error Messages
4142 @section Error Messages From @code{find}
4144 @table @samp
4145 @item invalid predicate `-foo'
4146 This means that the @code{find} command line included something that
4147 started with a dash or other special character.  The @code{find}
4148 program tried to interpret this as a test, action or option, but
4149 didn't recognise it.  If it was intended to be a test, check what was
4150 specified against the documentation.  If, on the other hand, the
4151 string is the name of a file which has been expanded from a wildcard
4152 (for example because you have a @samp{*} on the command line),
4153 consider using @samp{./*} or just @samp{.} instead.
4155 @item unexpected extra predicate
4156 This usually happens if you have an extra bracket on the command line
4157 (for example @samp{find . -print \)}).
4159 @item Warning: filesystem /path/foo has recently been mounted
4160 @itemx Warning: filesystem /path/foo has recently been unmounted
4161 These messages might appear when @code{find} moves into a directory
4162 and finds that the device number and inode are different to what it
4163 expected them to be.  If the directory @code{find} has moved into is
4164 on an network filesystem (NFS), it will not issue this message, because
4165 @code{automount} frequently mounts new filesystems on directories as
4166 you move into them (that is how it knows you want to use the
4167 filesystem).  So, if you do see this message, be wary ---
4168 @code{automount} may not have been responsible.  Consider the
4169 possibility that someone else is manipulating the filesystem while
4170 @code{find} is running.  Some people might do this in order to mislead
4171 @code{find} or persuade it to look at one set of files when it thought
4172 it was looking at another set.
4174 @item /path/foo changed during execution of find (old device number 12345, new device number 6789, filesystem type is <whatever>) [ref XXX]
4175 This message is issued when @code{find} moves into a directory and ends up
4176 somewhere it didn't expect to be.  This happens in one of two
4177 circumstances.  Firstly, this happens when @code{automount} intervenes
4178 on a system where @code{find} doesn't know how to determine what
4179 the current set of mounted filesystems is.
4181 Secondly, this can happen when the device number of a directory
4182 appears to change during a change of current directory, but
4183 @code{find} is moving up the filesystem hierarchy rather than down into it.
4184 In order to prevent @code{find} wandering off into some unexpected
4185 part of the filesystem, we stop it at this point.
4187 @item Don't know how to use getmntent() to read `/etc/mtab'.  This is a bug.
4188 This message is issued when a problem similar to the above occurs on a
4189 system where @code{find} doesn't know how to figure out the current
4190 list of mount points.  Ask for help on @email{bug-findutils@@gnu.org}.
4192 @item /path/foo/bar changed during execution of find (old inode number 12345, new inode number 67893, filesystem type is <whatever>) [ref XXX]"),
4193 This message is issued when @code{find} moves into a directory and
4194 discovers that the inode number of that directory
4195 is different from the inode number that it obtained when it examined the
4196 directory previously.  This usually means that while
4197 @code{find} was deep in a directory hierarchy doing a
4198 time consuming operation, somebody has moved one of the parent directories to
4199 another location in the same filesystem.  This may or may not have been done
4200 maliciously.  In any case, @code{find} stops at this point
4201 to avoid traversing parts of the filesystem that it wasn't
4202 intended.  You can use @code{ls -li} or @code{find /path -inum
4203 12345 -o -inum 67893} to find out more about what has happened.
4205 @item sanity check of the fnmatch() library function failed.
4206 Please submit a bug report.  You may well be asked questions about
4207 your system, and if you compiled the @code{findutils} code yourself,
4208 you should keep your copy of the build tree around.  The likely
4209 explanation is that your system has a buggy implementation of
4210 @code{fnmatch} that looks enough like the GNU version to fool
4211 @code{configure}, but which doesn't work properly.
4213 @item cannot fork
4214 This normally happens if you use the @code{-exec} action or
4215 something similar (@code{-ok} and so forth) but the system has run out
4216 of free process slots.  This is either because the system is very busy
4217 and the system has reached its maximum process limit, or because you
4218 have a resource limit in place and you've reached it.  Check the
4219 system for runaway processes (with @code{ps}, if possible).  Some process
4220 slots are normally reserved for use by @samp{root}.
4222 @item some-program terminated by signal 99
4223 Some program which was launched with @code{-exec} or similar was killed
4224 with a fatal signal.  This is just an advisory message.
4225 @end table
4228 @node Error Messages From xargs, Error Messages From locate, Error Messages From find, Error Messages
4229 @section Error Messages From xargs
4231 @table @samp
4232 @item environment is too large for exec
4233 This message means that you have so many environment variables set (or
4234 such large values for them) that there is no room within the
4235 system-imposed limits on program command line argument length to
4236 invoke any program.  This is an unlikely situation and is more likely
4237 result of an attempt to test the limits of @code{xargs}, or break it.
4238 Please try unsetting some environment variables, or exiting the
4239 current shell.
4241 @item can not fit single argument within argument list size limit
4242 You are using the @samp{-I} option and @code{xargs} doesn't have
4243 enough space to build a command line because it has read a really
4244 large item and it doesn't fit.  You can probably work around this
4245 problem with the @samp{-s} option, but the default size is pretty
4246 large.  This is a rare situation and is more likely an attempt to test
4247 the limits of @code{xargs}, or break it.  Otherwise, you will need to
4248 try to shorten the problematic argument or not use @code{xargs}.
4250 @item cannot fork
4251 See the description of the similar message for @code{find}.
4253 @item <program>: exited with status 255; aborting
4254 When a command run by @code{xargs} exits with status 255, @code{xargs}
4255 is supposed to stop.  If this is not what you intended, wrap the
4256 program you are trying to invoke in a shell script which doesn't
4257 return status 255.
4259 @item <program>: terminated by signal 99
4260 See the description of the similar message for @code{find}.
4261 @end table
4263 @node Error Messages From locate, Error Messages From updatedb, Error Messages From xargs, Error Messages
4264 @section Error Messages From @code{locate}
4266 @table @samp
4267 @item warning: database `/usr/local/var/locatedb' is more than 8 days old
4268 The @code{locate} program relies on a database which is periodically
4269 built by the @code{updatedb} program.  That hasn't happened in a long
4270 time.  To fix this problem, run @code{updatedb} manually.  This can
4271 often happen on systems that are generally not left on, so the
4272 periodic ``cron'' task which normally does this doesn't get a chance
4273 to run.
4275 @item locate database `/usr/local/var/locatedb' is corrupt or invalid
4276 This should not happen.  Re-run @code{updatedb}.  If that works, but
4277 @code{locate} still produces this error, run @code{locate --version}
4278 and @code{updatedb --version}.  These should produce the same output.
4279 If not, you are using a mixed toolset; check your @samp{$PATH}
4280 environment variable and your shell aliases (if you have any).  If
4281 both programs claim to be GNU versions, this is a bug; all versions of
4282 these programs should interoperate without problem.  Ask for help on
4283 @email{bug-findutils@@gnu.org}.
4284 @end table
4287 @node Error Messages From updatedb, , Error Messages From locate, Error Messages
4288 @section Error Messages From updatedb
4290 The @code{updatedb} program (and the programs it invokes) do issue
4291 error messages, but none seem to be candidates for guidance.  If
4292 you are having a problem understanding one of these, ask for help on
4293 @email{bug-findutils@@gnu.org}.
4295 @node Primary Index, , Error Messages, Top
4296 @unnumbered @code{find} Primary Index
4298 This is a list of all of the primaries (tests, actions, and options)
4299 that make up @code{find} expressions for selecting files.  @xref{find
4300 Expressions}, for more information on expressions.
4302 @printindex fn
4304 @bye
4306 @comment texi related words used by Emacs' spell checker ispell.el
4308 @comment LocalWords: texinfo setfilename settitle setchapternewpage
4309 @comment LocalWords: iftex finalout ifinfo DIR titlepage vskip pt
4310 @comment LocalWords: filll dir samp dfn noindent xref pxref
4311 @comment LocalWords: var deffn texi deffnx itemx emph asis
4312 @comment LocalWords: findex smallexample subsubsection cindex
4313 @comment LocalWords: dircategory direntry itemize
4315 @comment other words used by Emacs' spell checker ispell.el
4316 @comment LocalWords: README fred updatedb xargs Plett Rendell akefile
4317 @comment LocalWords: args grep Filesystems fo foo fOo wildcards iname
4318 @comment LocalWords: ipath regex iregex expr fubar regexps
4319 @comment LocalWords: metacharacters macs sr sc inode lname ilname
4320 @comment LocalWords: sysdep noleaf ls inum xdev filesystems usr atime
4321 @comment LocalWords: ctime mtime amin cmin mmin al daystart Sladkey rm
4322 @comment LocalWords: anewer cnewer bckw rf xtype uname gname uid gid
4323 @comment LocalWords: nouser nogroup chown chgrp perm ch maxdepth
4324 @comment LocalWords: mindepth cpio src CD AFS statted stat fstype ufs
4325 @comment LocalWords: nfs tmp mfs printf fprint dils rw djm Nov lwall
4326 @comment LocalWords: POSIXLY fls fprintf strftime locale's EDT GMT AP
4327 @comment LocalWords: EST diff perl backquotes sprintf Falstad Oct cron
4328 @comment LocalWords: eg vmunix mkdir afs allexec allwrite ARG bigram
4329 @comment LocalWords: bigrams cd chmod comp crc CVS dbfile dum eof
4330 @comment LocalWords: fileserver filesystem fn frcode Ghazi Hnewc iXX
4331 @comment LocalWords: joeuser Kaveh localpaths localuser LOGNAME
4332 @comment LocalWords: Meyering mv netpaths netuser nonblank nonblanks
4333 @comment LocalWords: ois ok Pinard printindex proc procs prunefs
4334 @comment LocalWords: prunepaths pwd RFS rmadillo rmdir rsh sbins str
4335 @comment LocalWords: su Timar ubins ug unstripped vf VM Weitzel
4336 @comment LocalWords: wildcard zlogout basename execdir wholename iwholename
4337 @comment LocalWords: timestamp timestamps Solaris FreeBSD OpenBSD POSIX