Reordered the sections in the manual to put the "Common Tasks" and
[findutils.git] / doc / find.texi
blob39b90ef8327d7b018bfc2efb34bc96d2d89eaffd
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.
2092 @end deffn
2094 @deffn Action -ok command ;
2095 This insecure variant of the @samp{-okdir} action is specified by
2096 POSIX.  The main difference is that the command is executed in the
2097 directory from which @code{find} was invoked, meaning that @samp{@{@}}
2098 is expanded to a relative path starting with the name of one of the
2099 starting directories, rather than just the basename of the matched
2100 file.
2101 @end deffn
2103 When processing multiple files with a single command, to query the
2104 user you give @code{xargs} the following option.  When using this
2105 option, you might find it useful to control the number of files
2106 processed per invocation of the command (@pxref{Limiting Command
2107 Size}).
2109 @table @code
2110 @item --interactive
2111 @itemx -p
2112 Prompt the user about whether to run each command line and read a line
2113 from the terminal.  Only run the command line if the response starts
2114 with @samp{y} or @samp{Y}.  Implies @samp{-t}.
2115 @end table
2117 @node Delete Files
2118 @section Delete Files
2120 @deffn Action -delete
2121 Delete files or directories; true if removal succeeded.  If the
2122 removal failed, an error message is issued.
2124 The use of the @samp{-delete} action on the command line automatically
2125 turns on the @samp{-depth} option (@pxref{find Expressions}).
2126 @end deffn
2128 @node Adding Tests
2129 @section Adding Tests
2131 You can test for file attributes that none of the @code{find} builtin
2132 tests check.  To do this, use @code{xargs} to run a program that
2133 filters a list of files printed by @code{find}.  If possible, use
2134 @code{find} builtin tests to pare down the list, so the program run by
2135 @code{xargs} has less work to do.  The tests builtin to @code{find}
2136 will likely run faster than tests that other programs perform.
2138 For reasons of efficiency it is often useful to limit the number of
2139 times an external program has to be run.  For this reason, it is often
2140 a good idea to implement ``extended'' tests by using @code{xargs}.
2142 For example, here is a way to print the names of all of the unstripped
2143 binaries in the @file{/usr/local} directory tree.  Builtin tests avoid
2144 running @code{file} on files that are not regular files or are not
2145 executable.
2147 @example
2148 find /usr/local -type f -perm /a=x | xargs file |
2149   grep 'not stripped' | cut -d: -f1
2150 @end example
2152 @noindent
2153 The @code{cut} program removes everything after the file name from the
2154 output of @code{file}.
2156 However, using @code{xargs} can present important security problems
2157 (@pxref{Security Considerations}).  These can be avoided by using
2158 @samp{-execdir}.  The @samp{-execdir} action is also a useful way of
2159 putting your own test in the middle of a set of other tests or actions
2160 for @code{find} (for example, you might want to use @samp{-prune}).
2162 @c Idea from Martin Weitzel.
2163 To place a special test somewhere in the middle of a @code{find}
2164 expression, you can use @samp{-execdir} (or, less securely,
2165 @samp{-exec}) to run a program that performs the test.  Because
2166 @samp{-execdir} evaluates to the exit status of the executed program,
2167 you can use a program (which can be a shell script) that tests for a
2168 special attribute and make it exit with a true (zero) or false
2169 (non-zero) status.  It is a good idea to place such a special test
2170 @emph{after} the builtin tests, because it starts a new process which
2171 could be avoided if a builtin test evaluates to false.
2173 Here is a shell script called @code{unstripped} that checks whether
2174 its argument is an unstripped binary file:
2176 @example
2177 #! /bin/sh
2178 file "$1" | grep -q "not stripped"
2179 @end example
2182 This script relies on the shell exiting with the status of
2183 the last command in the pipeline, in this case @code{grep}.  The
2184 @code{grep} command exits with a true status if it found any matches,
2185 false if not.  Here is an example of using the script (assuming it is
2186 in your search path).  It lists the stripped executables (and shell
2187 scripts) in the file @file{sbins} and the unstripped ones in
2188 @file{ubins}.
2190 @example
2191 find /usr/local -type f -perm /a=x \
2192   \( -execdir unstripped '@{@}' \; -fprint ubins -o -fprint sbins \)
2193 @end example
2196 @node Databases, File Permissions, Actions, Top
2197 @chapter File Name Databases
2199 The file name databases used by @code{locate} contain lists of files
2200 that were in particular directory trees when the databases were last
2201 updated.  The file name of the default database is determined when
2202 @code{locate} and @code{updatedb} are configured and installed.  The
2203 frequency with which the databases are updated and the directories for
2204 which they contain entries depend on how often @code{updatedb} is run,
2205 and with which arguments.
2207 You can obtain some statistics about the databases by using
2208 @samp{locate --statistics}.
2210 @menu
2211 * Database Locations::
2212 * Database Formats::
2213 * Newline Handling::
2214 @end menu
2217 @node Database Locations
2218 @section Database Locations
2220 There can be multiple file name databases.  Users can select which
2221 databases @code{locate} searches using the @code{LOCATE_PATH}
2222 environment variable or a command line option.  The system
2223 administrator can choose the file name of the default database, the
2224 frequency with which the databases are updated, and the directories
2225 for which they contain entries.  File name databases are updated by
2226 running the @code{updatedb} program, typically nightly.
2228 In networked environments, it often makes sense to build a database at
2229 the root of each filesystem, containing the entries for that
2230 filesystem.  @code{updatedb} is then run for each filesystem on the
2231 fileserver where that filesystem is on a local disk, to prevent
2232 thrashing the network.
2234 @xref{Invoking updatedb},
2235 for the description of the options to @code{updatedb}, which specify
2236 which directories would each database contain entries for.
2239 @node Database Formats
2240 @section Database Formats
2242 The file name databases contain lists of files that were in particular
2243 directory trees when the databases were last updated.  The file name
2244 database format changed starting with GNU @code{locate} version 4.0 to
2245 allow machines with different byte orderings to share the databases.
2246 The new GNU @code{locate} can read both the old and new database
2247 formats.  However, old versions of @code{locate} and @code{find}
2248 produce incorrect results if given a new-format database.
2250 If you run @samp{locate --statistics}, the resulting summary indicates
2251 the type of each @code{locate} database.
2254 @menu
2255 * New Database Format::
2256 * Sample Database::
2257 * Old Database Format::
2258 @end menu
2260 @node New Database Format
2261 @subsection New Database Format
2263 @code{updatedb} runs a program called @code{frcode} to
2264 @dfn{front-compress} the list of file names, which reduces the
2265 database size by a factor of 4 to 5.  Front-compression (also known as
2266 incremental encoding) works as follows.
2268 The database entries are a sorted list (case-insensitively, for users'
2269 convenience).  Since the list is sorted, each entry is likely to share
2270 a prefix (initial string) with the previous entry.  Each database
2271 entry begins with an offset-differential count byte, which is the
2272 additional number of characters of prefix of the preceding entry to
2273 use beyond the number that the preceding entry is using of its
2274 predecessor.  (The counts can be negative.)  Following the count is a
2275 null-terminated ASCII remainder---the part of the name that follows
2276 the shared prefix.
2278 If the offset-differential count is larger than can be stored in a
2279 byte (+/-127), the byte has the value 0x80 and the count follows in a
2280 2-byte word, with the high byte first (network byte order).
2282 Every database begins with a dummy entry for a file called
2283 @file{LOCATE02}, which @code{locate} checks for to ensure that the
2284 database file has the correct format; it ignores the entry in doing
2285 the search.
2287 Databases cannot be concatenated together, even if the first (dummy)
2288 entry is trimmed from all but the first database.  This is because the
2289 offset-differential count in the first entry of the second and
2290 following databases will be wrong.
2292 In the output of @samp{locate --statistics}, the new database format
2293 is referred to as @samp{LOCATE02}.
2295 @node Sample Database
2296 @subsection Sample Database
2298 Sample input to @code{frcode}:
2299 @c with nulls changed to newlines:
2301 @example
2302 /usr/src
2303 /usr/src/cmd/aardvark.c
2304 /usr/src/cmd/armadillo.c
2305 /usr/tmp/zoo
2306 @end example
2308 Length of the longest prefix of the preceding entry to share:
2310 @example
2311 0 /usr/src
2312 8 /cmd/aardvark.c
2313 14 rmadillo.c
2314 5 tmp/zoo
2315 @end example
2317 Output from @code{frcode}, with trailing nulls changed to newlines
2318 and count bytes made printable:
2320 @example
2321 0 LOCATE02
2322 0 /usr/src
2323 8 /cmd/aardvark.c
2324 6 rmadillo.c
2325 -9 tmp/zoo
2326 @end example
2328 (6 = 14 - 8, and -9 = 5 - 14)
2330 @node Old Database Format
2331 @subsection Old Database Format
2333 The old database format is used by Unix @code{locate} and @code{find}
2334 programs and earlier releases of the GNU ones.  @code{updatedb}
2335 produces this format if given the @samp{--old-format} option.
2337 @code{updatedb} runs programs called @code{bigram} and @code{code} to
2338 produce old-format databases.  The old format differs from the new one
2339 in the following ways.  Instead of each entry starting with an
2340 offset-differential count byte and ending with a null, byte values
2341 from 0 through 28 indicate offset-differential counts from -14 through
2342 14.  The byte value indicating that a long offset-differential count
2343 follows is 0x1e (30), not 0x80.  The long counts are stored in host
2344 byte order, which is not necessarily network byte order, and host
2345 integer word size, which is usually 4 bytes.  They also represent a
2346 count 14 less than their value.  The database lines have no
2347 termination byte; the start of the next line is indicated by its first
2348 byte having a value <= 30.
2350 In addition, instead of starting with a dummy entry, the old database
2351 format starts with a 256 byte table containing the 128 most common
2352 bigrams in the file list.  A bigram is a pair of adjacent bytes.
2353 Bytes in the database that have the high bit set are indexes (with the
2354 high bit cleared) into the bigram table.  The bigram and
2355 offset-differential count coding makes these databases 20-25% smaller
2356 than the new format, but makes them not 8-bit clean.  Any byte in a
2357 file name that is in the ranges used for the special codes is replaced
2358 in the database by a question mark, which not coincidentally is the
2359 shell wildcard to match a single character.
2361 The old format therefore cannot faithfully store entries with
2362 non-ASCII characters. It therefore should not be used in
2363 internationalized environments.
2365 The output of @samp{locate --statistics} will give an incorrect count
2366 of the number of file names containing newlines or high-bit characters
2367 for old-format databases.
2369 @node Newline Handling
2370 @section Newline Handling
2372 Within the database, file names are terminated with a null character.
2373 This is the case for both the old and the new format.
2375 When the new database format is being used, the compression technique
2376 used to generate the database though relies on the ability to sort the
2377 list of files before they are presented to @code{frcode}.
2379 If the system's sort command allows its input list of files to be
2380 separated with null characters via the @samp{-z} option, this option
2381 is used and therefore @code{updatedb} and @code{locate} will both
2382 correctly handle file names containing newlines.  If the @code{sort}
2383 command lacks support for this, the list of files is delimited with
2384 the newline character, meaning that parts of file names containing
2385 newlines will be incorrectly sorted.  This can result in both
2386 incorrect matches and incorrect failures to match.
2388 On the other hand, if you are using the old database format, file
2389 names with embedded newlines are not correctly handled.  There is no
2390 technical limitation which enforces this, it's just that the
2391 @code{bigram} program has not been updated to support lists of file
2392 names separated by nulls.
2394 So, if you are using the new database format (this is the default) and
2395 your system uses GNU @code{sort}, newlines will be correctly handled
2396 at all times.  Otherwise, newlines may not be correctly handled.
2398 @node File Permissions, Reference, Databases, Top
2399 @chapter File Permissions
2401 @include perm.texi
2403 @node Reference, Common Tasks, File Permissions, Top
2404 @chapter Reference
2406 Below are summaries of the command line syntax for the programs
2407 discussed in this manual.
2409 @menu
2410 * Invoking find::
2411 * Invoking locate::
2412 * Invoking updatedb::
2413 * Invoking xargs::
2414 * Regular Expressions::
2415 @end menu
2417 @node Invoking find, Invoking locate, , Reference
2418 @section Invoking @code{find}
2420 @example
2421 find @r{[-H] [-L] [-P]} @r{[}@var{file}@dots{}@r{]} @r{[}@var{expression}@r{]}
2422 @end example
2424 @code{find} searches the directory tree rooted at each file name
2425 @var{file} by evaluating the @var{expression} on each file it finds in
2426 the tree.
2428 The options @samp{-H}, @samp{-L} or @samp{-P} may be specified at the
2429 start of the command line (if none of these is specified, @samp{-P} is
2430 assumed).  The arguments after these are a list of files or
2431 directories that should be searched.
2433 This list of files to search is followed by a list of expressions
2434 describing the files we wish to search for.  The first part of the
2435 expression is recognised by the fact that it begins with @samp{-},
2436 @samp{(}, @samp{)}, @samp{,}, or @samp{!}.  Any arguments after it are
2437 the rest of the expression.  If no files are given, the current
2438 directory is used.  If no expression is given, the expression
2439 @samp{-print} is used.
2441 @code{find} exits with status zero if all files matched are processed
2442 successfully, greater than 0 if errors occur.
2444 Three options can precede the list of files.  They determine the
2445 way that symbolic links are handled.
2447 @table @code
2448 @item -P
2449 Never follow symbolic links (this is the default), except in the case
2450 of the @samp{-xtype} predicate.
2451 @item -L
2452 Always follow symbolic links, except in the case of the @samp{-xtype}
2453 predicate.
2454 @item -H
2455 Follow symbolic links specified in the list of files to search, or
2456 which are otherwise specified on the command line.
2457 @end table
2459 If @code{find} would follow a symbolic link, but cannot for any reason
2460 (for example, because it has insufficient permissions or the link is
2461 broken), it falls back on using the properties of the symbolic link
2462 itself.  @ref{Symbolic Links} for a more complete description of how
2463 symbolic links are handled.
2465 @xref{Primary Index}, for a summary of all of the tests, actions, and
2466 options that the expression can contain.  If the expression is
2467 missing, @samp{-print} is assumed.
2470 @code{find} also recognizes two options for administrative use:
2472 @table @code
2473 @item --help
2474 Print a summary of the command line usage and exit.
2475 @item --version
2476 Print the version number of @code{find} and exit.
2477 @end table
2480 @menu
2481 * Warning Messages::
2482 @end menu
2485 @node Warning Messages,,, Invoking find
2486 @subsection Warning Messages
2488 If there is an error on the @code{find} command line, an error message
2489 is normally issued.  However, there are some usages that are
2490 inadvisable but which @code{find} should still accept.  Under these
2491 circumstances, @code{find} may issue a warning message.  By default,
2492 warnings are enabled only if @code{find} is being run interactively
2493 (specifically, if the standard input is a terminal).  Warning messages
2494 can be controlled explicitly by the use of options on the command
2495 line:
2497 @table @code
2498 @item -warn
2499 Issue warning messages where appropriate.
2500 @item -nowarn
2501 Do not issue warning messages.
2502 @end table
2504 These options take effect at the point on the command line where they
2505 are specified.  Therefore if you specify @samp{-nowarn} at the end of
2506 the command line, you will not see warning messages for any problems
2507 occurring before that.  The warning messages affected by the above
2508 options are triggered by:
2510 @itemize @minus
2511 @item
2512 Use of the @samp{-d} option which is deprecated; please use
2513 @samp{-depth} instead, since the latter is POSIX-compliant.
2514 @item
2515 Use of the @samp{-ipath} option which is deprecated; please use
2516 @samp{-iwholename} instead.
2517 @item
2518 Specifying an option (for example @samp{-mindepth}) after a non-option
2519 (for example @samp{-type} or @samp{-print}) on the command line.
2520 @end itemize
2523 The default behaviour above is designed to work in that way so that
2524 existing shell scripts which use such constructs don't generate
2525 spurious errors, but people will be made aware of the problem.
2527 Some warning messages are issued for less common or more serious
2528 problems, and consequently cannot be turned off:
2530 @itemize @minus
2531 @item
2532 Use of an unrecognised backslash escape sequence with @samp{-fprintf}
2533 @item
2534 Use of an unrecognised formatting directive with @samp{-fprintf}
2535 @end itemize
2537 @node Invoking locate, Invoking updatedb, Invoking find, Reference
2538 @section Invoking @code{locate}
2540 @example
2541 locate @r{[}@var{option}@dots{}@r{]} @var{pattern}@dots{}
2542 @end example
2544 For each @var{pattern} given @code{locate} searches one or more file
2545 name databases returning each match of @var{pattern}.
2547 For each @var{pattern} given @code{locate} searches one or more file
2548 name databases returning each match of @var{pattern}.
2550 @table @code
2551 @item --all
2552 @itemx -A
2553 Print only names which match all non-option arguments, not those
2554 matching one or more non-option arguments.
2556 @item --basename
2557 @itemx -b
2558 The specified pattern is matched against just the last component of
2559 the name of a file in the @code{locate} database.  This last
2560 component is also called the ``base name''.  For example, the base
2561 name of @file{/tmp/mystuff/foo.old.c} is @file{foo.old.c}.  If the
2562 pattern contains metacharacters, it must match the base name exactly.
2563 If not, it must match part of the base name.
2565 @item --count
2566 @itemx -c
2567 Instead of printing the matched file names, just print the total
2568 number of matches found, unless @samp{--print} (@samp{-p}) is also
2569 present.
2572 @item --database=@var{path}
2573 @itemx -d @var{path}
2574 Instead of searching the default @code{locate} database, @code{locate} search the file
2575 name databases in @var{path}, which is a colon-separated list of
2576 database file names.  You can also use the environment variable
2577 @code{LOCATE_PATH} to set the list of database files to search.  The
2578 option overrides the environment variable if both are used.  Empty
2579 elements in @var{path} (that is, a leading or trailing colon, or two
2580 colons in a row) are taken to stand for the default database.
2581 A database can be supplied on stdin, using @samp{-} as an element
2582 of @samp{path}. If more than one element of @samp{path} is @samp{-},
2583 later instances are ignored (but a warning message is printed).
2585 @item --existing
2586 @itemx -e
2587 Only print out such names which currently exist (instead of such names
2588 which existed when the database was created).  Note that this may slow
2589 down the program a lot, if there are many matches in the database.
2590 The way in which broken symbolic links are treated is affected by the
2591 @samp{-L}, @samp{-P} and @samp{-H} options.
2593 @item --non-existing
2594 @itemx -E
2595 Only print out such names which currently do not exist (instead of
2596 such names which existed when the database was created).  Note that
2597 this may slow down the program a lot, if there are many matches in the
2598 database.  The way in which broken symbolic links are treated is
2599 affected by the @samp{-L}, @samp{-P} and @samp{-H} options.
2601 @item --follow
2602 @itemx -L
2603 If testing for the existence of files (with the @samp{-e} or @samp{-E}
2604 options), consider broken symbolic links to be non-existing.  This is
2605 the default behaviour.
2608 @item --nofollow
2609 @itemx -P
2610 @itemx -H
2611 If testing for the existence of files (with the @samp{-e} or @samp{-E}
2612 options), treat broken symbolic links as if they were existing files.
2613 The @samp{-H} form of this option is provided purely for similarity
2614 with @code{find}; the use of @samp{-P} is recommended over @samp{-H}.
2616 @item --ignore-case
2617 @itemx -i
2618 Ignore case distinctions in both the pattern and the file names.
2620 @item --limit=N
2621 @itemx -l N
2622 Limit the number of results printed to N.  When used with the
2623 @samp{--count} option, the value printed will never be larger than
2624 this limit.
2626 @item --mmap
2627 @itemx -m
2628 Accepted but does nothing.  The option is supported only to provide
2629 compatibility with BSD's @code{locate}.
2631 @item --null
2632 @itemx -0
2633 Results are separated with the ASCII NUL character rather than the
2634 newline character.  To get the full benefit of the use of this option,
2635 use the new @code{locate} database format (that is the default
2636 anyway).
2638 @item --print
2639 @itemx -p
2640 Print search results when they normally would not, because of the
2641 presence of @samp{--statistics} (@samp{-S}) or @samp{--count}
2642 (@samp{-c}).
2644 @item --wholename
2645 @itemx -w
2646 The specified pattern is matched against the whole name of the file in
2647 the @code{locate} database.  If the pattern contains metacharacters,
2648 it must match exactly.  If not, it must match part of the whole file
2649 name.  This is the default behaviour.
2651 @item --regex
2652 @itemx -r
2653 Instead of using substring or shell glob matching, the pattern
2654 specified on the command line is understood to be a regular
2655 expression.  GNU Emacs-style regular expressions are assumed unless
2656 the @samp{--regextype} option is also given.  File names from the
2657 @code{locate} database are matched using the specified regular
2658 expression.  If the @samp{-i} flag is also given, matching is
2659 case-insensitive.  Matches are performed against the whole path name,
2660 and so by default a pathname will be matched if any part of it matches
2661 the specified regular expression.  The regular expression may use
2662 @samp{^} or @samp{$} to anchor a match at the beginning or end of a
2663 pathname.
2665 @item --regextype
2666 This option changes the regular expression dialect used.  Dialects
2667 understood are described in @ref{Regular Expressions}.
2671 @item --regextype
2672 This option changes the regular expression syntax and behaviour used
2673 by the @samp{--regex} option.  @ref{Regular Expressions} for more
2674 information on the regular expression dialects understood by GNU
2675 findutils.
2677 @item --stdio
2678 @itemx -s
2679 Accepted but does nothing.  The option is supported only to provide
2680 compatibility with BSD's @code{locate}.
2682 @item --statistics
2683 @itemx -S
2684 Print some summary information for each @code{locate} database.  No
2685 search is performed unless non-option arguments are given.
2687 @item --help
2688 Print a summary of the command line usage for @code{locate} and exit.
2690 @item --version
2691 Print the version number of @code{locate} and exit.
2692 @end table
2694 @node Invoking updatedb, Invoking xargs, Invoking locate, Reference
2695 @section Invoking @code{updatedb}
2697 @example
2698 updatedb @r{[}@var{option}@dots{}@r{]}
2699 @end example
2701 @code{updatedb} creates and updates the database of file names used by
2702 @code{locate}.  @code{updatedb} generates a list of files similar to
2703 the output of @code{find} and then uses utilities for optimizing the
2704 database for performance.  @code{updatedb} is often run periodically
2705 as a @code{cron} job and configured with environment variables or
2706 command options.  Typically, operating systems have a shell script
2707 that ``exports'' configurations for variable definitions and uses
2708 another schell script that ``sources'' the configuration file into the
2709 environment and then executes @code{updatedb} in the environment.
2711 @code{updatedb} creates and updates the database of file names used by
2712 @code{locate}.  @code{updatedb} generates a list of files similar to
2713 the output of @code{find} and then uses utilities for optimizing the
2714 database for performance.  @code{updatedb} is often run periodically
2715 as a @code{cron} job and configured with environment variables or
2716 command options.  Typically, operating systems have a shell script
2717 that ``exports'' configurations for variable definitions and uses
2718 another schell script that ``sources'' the configuration file into the
2719 environment and then executes @code{updatedb} in the environment.
2721 @table @code
2722 @item --findoptions='@var{OPTION}@dots{}'
2723 Global options to pass on to @code{find}.
2724 The environment variable @code{FINDOPTIONS} also sets this value.
2725 Default is none.
2727 @item --localpaths='@var{path}@dots{}'
2728 Non-network directories to put in the database.
2729 Default is @file{/}.
2731 @item --netpaths='@var{path}@dots{}'
2732 Network (NFS, AFS, RFS, etc.) directories to put in the database.
2733 The environment variable @code{NETPATHS} also sets this value.
2734 Default is none.
2736 @item --prunepaths='@var{path}@dots{}'
2737 Directories to omit from the database, which would otherwise be
2738 included.  The environment variable @code{PRUNEPATHS} also sets this
2739 value.  Default is @file{/tmp /usr/tmp /var/tmp /afs}.  The paths are
2740 used as regular expressions (with @code{find ... -regex}, so you need
2741 to specify these paths in the same way that @code{find} will encounter
2742 them.  This means for example that the paths must not include trailing
2743 slashes.
2745 @item --prunefs='@var{path}@dots{}'
2746 Filesystems to omit from the database, which would otherwise be
2747 included.  Note that files are pruned when a filesystem is reached;
2748 Any filesystem mounted under an undesired filesystem will be ignored.
2749 The environment variable @code{PRUNEFS} also sets this value.  Default
2750 is @file{nfs NFS proc}.
2752 @item --output=@var{dbfile}
2753 The database file to build.  Default is system-dependent, but
2754 typically @file{/usr/local/var/locatedb}.
2756 @item --localuser=@var{user}
2757 The user to search the non-network directories as, using @code{su}.
2758 Default is to search the non-network directories as the current user.
2759 You can also use the environment variable @code{LOCALUSER} to set this user.
2761 @item --netuser=@var{user}
2762 The user to search network directories as, using @code{su}.  Default
2763 @code{user} is @code{daemon}.  You can also use the environment variable
2764 @code{NETUSER} to set this user.
2766 @item --old-format
2767 Generate a @code{locate} database in the old format, for compatibility
2768 with versions of @code{locate} other than GNU @code{locate}.  Using
2769 this option means that @code{locate} will not be able to properly
2770 handle non-ASCII characters in file names (that is, file names
2771 containing characters which have the eighth bit set, such as many of
2772 the characters from the ISO-8859-1 character set).
2773 @item --help
2774 Print a summary of the command line usage and exit.
2775 @item --version
2776 Print the version number of @code{updatedb} and exit.
2777 @end table
2779 @node Invoking xargs, Regular Expressions,  Invoking updatedb, Reference
2780 @section Invoking @code{xargs}
2782 @example
2783 xargs @r{[}@var{option}@dots{}@r{]} @r{[}@var{command} @r{[}@var{initial-arguments}@r{]}@r{]}
2784 @end example
2786 @code{xargs} exits with the following status:
2788 @table @asis
2789 @item 0
2790 if it succeeds
2791 @item 123
2792 if any invocation of the command exited with status 1-125
2793 @item 124
2794 if the command exited with status 255
2795 @item 125
2796 if the command is killed by a signal
2797 @item 126
2798 if the command cannot be run
2799 @item 127
2800 if the command is not found
2801 @item 1
2802 if some other error occurred.
2803 @end table
2805 @table @code
2806 @item --arg-file@r{=@var{inputfile}}
2807 @itemx -a o@r{@var{inputfile}}
2808 Read names from the file @var{inputfile} instead of standard input.
2810 @item --null
2811 @itemx -0
2812 Input file names are terminated by a null character instead of by
2813 whitespace, and any quotes and backslash characters are not considered special (every
2814 character is taken literally).  Disables the end of file string, which
2815 is treated like any other argument.
2817 @item --eof@r{[}=@var{eof-str}@r{]}
2818 @itemx -e@r{[}@var{eof-str}@r{]}
2819 Set the end of file string to @var{eof-str}.  If the end of file
2820 string occurs as a line of input, the rest of the input is ignored.
2821 If @var{eof-str} is omitted, there is no end of file string.  If this
2822 option is not given, the end of file string defaults to @samp{_}.
2824 @item --help
2825 Print a summary of the options to @code{xargs} and exit.
2827 @item --replace@r{[}=@var{replace-str}@r{]}
2828 @itemx -I@r{[}@var{replace-str}@r{]}
2829 @itemx -i@r{[}@var{replace-str}@r{]}
2830 Replace occurrences of @var{replace-str} in the initial arguments with
2831 names read from standard input.  Also, unquoted blanks do not
2832 terminate arguments; instead, the input is split at newlines only.
2833 If @var{replace-str} is omitted, it defaults to @samp{@{@}}
2834 (like for @samp{find -exec}).  Implies @samp{-x} and @samp{-l 1}.  @samp{-i} is
2835 depreceated in favour of @samp{-I}.
2837 @item --max-lines@r{[}=@var{max-lines}@r{]}
2838 @itemx -l@r{[}@var{max-lines}@r{]}
2839 Use at most @var{max-lines} non-blank input lines per command line;
2840 @var{max-lines} defaults to 1 if omitted.  Trailing blanks cause an
2841 input line to be logically continued on the next input line, for the
2842 purpose of counting the lines.  Implies @samp{-x}.
2844 @item --max-args=@var{max-args}
2845 @itemx -n @var{max-args}
2846 Use at most @var{max-args} arguments per command line.  Fewer than
2847 @var{max-args} arguments will be used if the size (see the @samp{-s}
2848 option) is exceeded, unless the @samp{-x} option is given, in which
2849 case @code{xargs} will exit.
2851 @item --interactive
2852 @itemx -p
2853 Prompt the user about whether to run each command line and read a line
2854 from the terminal.  Only run the command line if the response starts
2855 with @samp{y} or @samp{Y}.  Implies @samp{-t}.
2857 @item --no-run-if-empty
2858 @itemx -r
2859 If the standard input is completely empty, do not run the
2860 command.  By default, the command is run once even if there is no
2861 input.
2863 @item --max-chars=@var{max-chars}
2864 @itemx -s @var{max-chars}
2865 Use at most @var{max-chars} characters per command line, including the
2866 command, initial arguments and any terminating nulls at the ends of
2867 the argument strings.
2869 @item --verbose
2870 @itemx -t
2871 Print the command line on the standard error output before executing
2874 @item --version
2875 Print the version number of @code{xargs} and exit.
2877 @item --exit
2878 @itemx -x
2879 Exit if the size (see the @samp{-s} option) is exceeded.
2882 @item --max-procs=@var{max-procs}
2883 @itemx -P @var{max-procs}
2884 Run simultaneously up to @var{max-procs} processes at once; the default is 1.  If
2885 @var{max-procs} is 0, @code{xargs} will run as many processes as
2886 possible simultaneously.
2887 @end table
2890 @node Regular Expressions,, Invoking xargs, Reference
2891 @section Regular Expressions
2893 The @samp{-regex} and @samp{-iregex} tests of @code{find} allow
2894 matching by regular expression, as does the @samp{--regex} option of
2895 @code{locate}.  There are many different types of Regular Expression,
2896 but the type used by @code{find} and @code{locate} is the same as is
2897 used in GNU Emacs.  Both programs provide an option which allows you
2898 to select an alternative regular expression syntax; for @code{find}
2899 this is the @samp{-regextype} option, and for @code{locate} this is
2900 the @samp{--regextype} option.
2902 These options take a single argument, which indicates the specific
2903 regular expression syntax and behaviour that should be used.  This
2904 should be one of the following:
2906 @include regexprops.texi
2909 @node Common Tasks, Worked Examples, Reference, Top
2910 @chapter Common Tasks
2912 The sections that follow contain some extended examples that both give
2913 a good idea of the power of these programs, and show you how to solve
2914 common real-world problems.
2916 @menu
2917 * Viewing And Editing::
2918 * Archiving::
2919 * Cleaning Up::
2920 * Strange File Names::
2921 * Fixing Permissions::
2922 * Classifying Files::
2923 @end menu
2925 @node Viewing And Editing
2926 @section Viewing And Editing
2928 To view a list of files that meet certain criteria, simply run your
2929 file viewing program with the file names as arguments.  Shells
2930 substitute a command enclosed in backquotes with its output, so the
2931 whole command looks like this:
2933 @example
2934 less `find /usr/include -name '*.h' | xargs grep -l mode_t`
2935 @end example
2937 @noindent
2938 You can edit those files by giving an editor name instead of a file
2939 viewing program:
2941 @example
2942 emacs `find /usr/include -name '*.h' | xargs grep -l mode_t`
2943 @end example
2945 Because there is a limit to the length of any individual command line,
2946 there is a limit to the number of files that can be handled in this
2947 way.  We can get around this difficulty by using xargs like this:
2949 @example
2950 find /usr/include -name '*.h' | xargs grep -l mode_t > todo
2951 xargs --arg-file=todo emacs
2952 @end example
2954 Here, @code{xargs} will run @code{emacs} as many times as necessary to
2955 visit all of the files listed in the file @file{todo}.
2957 @node Archiving
2958 @section Archiving
2960 You can pass a list of files produced by @code{find} to a file
2961 archiving program.  GNU @code{tar} and @code{cpio} can both read lists
2962 of file names from the standard input---either delimited by nulls (the
2963 safe way) or by blanks (the lazy, risky default way).  To use
2964 null-delimited names, give them the @samp{--null} option.  You can
2965 store a file archive in a file, write it on a tape, or send it over a
2966 network to extract on another machine.
2968 One common use of @code{find} to archive files is to send a list of
2969 the files in a directory tree to @code{cpio}.  Use @samp{-depth} so if
2970 a directory does not have write permission for its owner, its contents
2971 can still be restored from the archive since the directory's
2972 permissions are restored after its contents.  Here is an example of
2973 doing this using @code{cpio}; you could use a more complex @code{find}
2974 expression to archive only certain files.
2976 @example
2977 find . -depth -print0 |
2978   cpio --create --null --format=crc --file=/dev/nrst0
2979 @end example
2981 You could restore that archive using this command:
2983 @example
2984 cpio --extract --null --make-dir --unconditional \
2985   --preserve --file=/dev/nrst0
2986 @end example
2988 Here are the commands to do the same things using @code{tar}:
2990 @example
2991 find . -depth -print0 |
2992   tar --create --null --files-from=- --file=/dev/nrst0
2994 tar --extract --null --preserve-perm --same-owner \
2995   --file=/dev/nrst0
2996 @end example
2998 @c Idea from Rick Sladkey.
2999 Here is an example of copying a directory from one machine to another:
3001 @example
3002 find . -depth -print0 | cpio -0o -Hnewc |
3003   rsh @var{other-machine} "cd `pwd` && cpio -i0dum"
3004 @end example
3006 @node Cleaning Up
3007 @section Cleaning Up
3009 @c Idea from Jim Meyering.
3010 This section gives examples of removing unwanted files in various
3011 situations.  Here is a command to remove the CVS backup files created
3012 when an update requires a merge:
3014 @example
3015 find . -name '.#*' -print0 | xargs -0r rm -f
3016 @end example
3018 The command above works, but the following is safer:
3020 @example
3021 find . -name '.#*' -depth -delete
3022 @end example
3024 @c Idea from Franc,ois Pinard.
3025 You can run this command to clean out your clutter in @file{/tmp}.
3026 You might place it in the file your shell runs when you log out
3027 (@file{.bash_logout}, @file{.logout}, or @file{.zlogout}, depending on
3028 which shell you use).
3030 @example
3031 find /tmp -depth -user "$LOGNAME" -type f -delete
3032 @end example
3034 If your @code{find} command removes directories, you may find that
3035 you get a spurious error message when @code{find} tries to recurse
3036 into a directory that has now been removed.  Using the @samp{-depth}
3037 option will normally resolve this problem.
3039 @c Idea from Noah Friedman.
3040 To remove old Emacs backup and auto-save files, you can use a command
3041 like the following.  It is especially important in this case to use
3042 null-terminated file names because Emacs packages like the VM mailer
3043 often create temporary file names with spaces in them, like
3044 @file{#reply to David J. MacKenzie<1>#}.
3046 @example
3047 find ~ \( -name '*~' -o -name '#*#' \) -print0 |
3048   xargs --no-run-if-empty --null rm -vf
3049 @end example
3051 Removing old files from @file{/tmp} is commonly done from @code{cron}:
3053 @c Idea from Kaveh Ghazi.
3054 @example
3055 find /tmp /var/tmp -not -type d -mtime +3 -delete
3056 find /tmp /var/tmp -depth -mindepth 1 -type d -empty -delete
3057 @end example
3059 The second @code{find} command above uses @samp{-depth} so it cleans
3060 out empty directories depth-first, hoping that the parents become
3061 empty and can be removed too.  It uses @samp{-mindepth} to avoid
3062 removing @file{/tmp} itself if it becomes totally empty.
3064 @node Strange File Names
3065 @section Strange File Names
3067 @c Idea from:
3068 @c From: tmatimar@isgtec.com (Ted Timar)
3069 @c Newsgroups: comp.unix.questions,comp.unix.shell,comp.answers,news.answers
3070 @c Subject: Unix - Frequently Asked Questions (2/7) [Frequent posting]
3071 @c Subject: How do I remove a file with funny characters in the filename ?
3072 @c Date: Thu Mar 18 17:16:55 EST 1993
3073 @code{find} can help you remove or rename a file with strange
3074 characters in its name.  People are sometimes stymied by files whose
3075 names contain characters such as spaces, tabs, control characters, or
3076 characters with the high bit set.  The simplest way to remove such
3077 files is:
3079 @example
3080 rm -i @var{some*pattern*that*matches*the*problem*file}
3081 @end example
3083 @code{rm} asks you whether to remove each file matching the given
3084 pattern.  If you are using an old shell, this approach might not work
3085 if the file name contains a character with the high bit set; the shell
3086 may strip it off.  A more reliable way is:
3088 @example
3089 find . -maxdepth 1 @var{tests} -okdir rm '@{@}' \;
3090 @end example
3092 @noindent
3093 where @var{tests} uniquely identify the file.  The @samp{-maxdepth 1}
3094 option prevents @code{find} from wasting time searching for the file
3095 in any subdirectories; if there are no subdirectories, you may omit
3096 it.  A good way to uniquely identify the problem file is to figure out
3097 its inode number; use
3099 @example
3100 ls -i
3101 @end example
3103 Suppose you have a file whose name contains control characters, and
3104 you have found that its inode number is 12345.  This command prompts
3105 you for whether to remove it:
3107 @example
3108 find . -maxdepth 1 -inum 12345 -okdir rm -f '@{@}' \;
3109 @end example
3111 If you don't want to be asked, perhaps because the file name may
3112 contain a strange character sequence that will mess up your screen
3113 when printed, then use @samp{-execdir} instead of @samp{-okdir}.
3115 If you want to rename the file instead, you can use @code{mv} instead
3116 of @code{rm}:
3118 @example
3119 find . -maxdepth 1 -inum 12345 -okdir mv '@{@}' @var{new-file-name} \;
3120 @end example
3122 @node Fixing Permissions
3123 @section Fixing Permissions
3125 Suppose you want to make sure that everyone can write to the
3126 directories in a certain directory tree.  Here is a way to find
3127 directories lacking either user or group write permission (or both),
3128 and fix their permissions:
3130 @example
3131 find . -type d -not -perm -ug=w | xargs chmod ug+w
3132 @end example
3134 @noindent
3135 You could also reverse the operations, if you want to make sure that
3136 directories do @emph{not} have world write permission.
3138 @node Classifying Files
3139 @section Classifying Files
3141 @c Idea from:
3142 @c From: martin@mwtech.UUCP (Martin Weitzel)
3143 @c Newsgroups: comp.unix.wizards,comp.unix.questions
3144 @c Subject: Advanced usage of 'find' (Re: Unix security automating script)
3145 @c Date: 22 Mar 90 15:05:19 GMT
3146 If you want to classify a set of files into several groups based on
3147 different criteria, you can use the comma operator to perform multiple
3148 independent tests on the files.  Here is an example:
3150 @example
3151 find / -type d \( -perm -o=w -fprint allwrite , \
3152   -perm -o=x -fprint allexec \)
3154 echo "Directories that can be written to by everyone:"
3155 cat allwrite
3156 echo ""
3157 echo "Directories with search permissions for everyone:"
3158 cat allexec
3159 @end example
3161 @code{find} has only to make one scan through the directory tree
3162 (which is one of the most time consuming parts of its work).
3164 @node Worked Examples, Security Considerations, Common Tasks, Top
3165 @chapter Worked Examples
3167 The tools in the findutils package, and in particular @code{find},
3168 have a large number of options.  This means that quite often,
3169 there is more than one way to do things.  Some of the options
3170 and facilities only exist for compatibility with other tools, and
3171 findutils provides improved ways of doing things.
3173 This chapter describes a number of useful tasks that are commonly
3174 performed, and compares the different ways of achieving them.
3176 @menu
3177 * Deleting Files::
3178 * Updating A Timestamp File::
3179 @end menu
3181 @node Deleting Files
3182 @section Deleting Files
3184 One of the most common tasks that @code{find} is used for is locating
3185 files that can be deleted.  This might include:
3187 @itemize
3188 @item 
3189 Files last modified more than 3 years ago which haven't been accessed
3190 for at least 2 years
3191 @item
3192 Files belonging to a certain user
3193 @item
3194 Temporary files which are no longer required
3195 @end itemize
3197 This example concentrates on the actual deletion task rather than on
3198 sophisticated ways of locatng the files that need to be deleted.
3199 We'll assume that the files we want to delete are old files underneath
3200 @file{/var/tmp/stuff}.
3202 @subsection The Traditional Way
3204 The traditional way to delete files in @file{var/tmp/stuff} that have
3205 not been modified in over 90 days would have been:
3207 @smallexample
3208 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \;
3209 @end smallexample
3211 The above command uses @samp{-exec} to run the @code{/bin/rm} command
3212 to remove each file.  This approach works and in fact would have
3213 worked in Version 7 Unix in 1979.  However, there are a number of
3214 problems with this approach.
3217 The most obvious problem with the approach above is that it causes
3218 @code{find} to fork every time it finds a file that needs to delete,
3219 and the child process then has to use the @code{exec} system call to
3220 launch @code{/bin/rm}.   All this is quite inefficient.  If we are
3221 going to use @code{/bin/rm} to do this job, it is better to make it
3222 delete more than one file at a time.  
3224 The most obvious way of doing this is to use the shell's command
3225 expansion feature:
3227 @smallexample
3228 /bin/rm `find /var/tmp/stuff -mtime +90 -print`
3229 @end smallexample
3230 or you could use the more modern form
3231 @smallexample
3232 /bin/rm $(find /var/tmp/stuff -mtime +90 -print)
3233 @end smallexample
3235 The commands above are much more efficient than the first attempt.
3236 However, there is a problem with them.  The shell has a maximum
3237 command length which is imposed by the operating system (the actual
3238 limit varies between systems).  This means that while the command
3239 expansion technique will usually work, it will suddenly fail when
3240 there are lots of files to delete.  Since the task is to delete
3241 unwanted files, this is precisely the time we don't want things to go
3242 wrong.
3244 @subsection Making Use of xargs
3246 So, is there a way to be more efficient in the use of @code{fork()}
3247 and @code{exec()} without running up against this limit?
3248 Yes, we can be almost optimally efficient by making use
3249 of the @code{xargs} command.  The @code{xargs} command reads arguments
3250 from its standard input and builds them into command lines.  We can
3251 use it like this:
3253 @smallexample
3254 find /var/tmp/stuff -mtime +90 -print | xargs /bin/rm 
3255 @end smallexample
3257 For example if the files found by @code{find} are
3258 @file{/var/tmp/stuff/A}, 
3259 @file{/var/tmp/stuff/B} and 
3260 @file{/var/tmp/stuff/C} then @code{xargs} might issue the commands 
3262 @smallexample
3263 /bin/rm /var/tmp/stuff/A /var/tmp/stuff/B
3264 /bin/rm /var/tmp/stuff/C
3265 @end smallexample
3267 The above assumes that @code{xargs} has a very small maximum command
3268 line length.  The real limit is much larger but the idea is that
3269 @code{xargs} will run @code{/bin/rm} as many times as necessary to get
3270 the job done, given the limits on command line length.
3272 This usage of @code{xargs} is pretty efficient, and the @code{xargs}
3273 command is widely implemented (all modern versions of Unix offer it).
3274 So far then, the news is all good.  However, there is bad news too.
3276 @subsection Unusual characters in filenames
3278 Unix-like systems allow any characters to appear in file names with
3279 the exception of the ASCII NUL character and the backslash.
3280 Backslashes can occur in path names (as the directory separator) but
3281 not in the names of actual directory entries.  This means that the
3282 list of files that @code{xargs} reads could in fact contain white space
3283 characters --- spaces, tabs and newline characters.  Since by default,
3284 @code{xargs} assumes that the list of files it is reading uses white
3285 space as an argument separator, it cannot correctly handle the case
3286 where a filename actually includes white space.  This makes the
3287 default behaviour of @code{xargs} almost useless for handling
3288 arbitrary data.
3290 To solve this problem, GNU findutils introduced the @samp{-print0}
3291 action for @code{find}.  This uses the ASCII NUL character to separate
3292 the entries in the file list that it produces.  This is the ideal
3293 choice of separator since it is the only character that cannot appear
3294 within a path name.  The @samp{-0} option to @code{xargs} makes it
3295 assume that arguments are separated with ASCII NUL instead of white
3296 space.  It also turns off another misfeature in the default behaviour
3297 of @code{xargs}, which is that it pays attention to quote characters
3298 in its input.  Some versions of @code{xargs} also terminate when they
3299 see a lone @samp{_} in the input, but GNU @code{find} no longer does
3300 that (since it has become an optional behaviour in the Unix standard).
3302 So, putting @code{find -print0} together with @code{xargs -0} we get
3303 this command:
3305 @smallexample
3306 find /var/tmp/stuff -mtime +90 -print0 | xargs -0 /bin/rm 
3307 @end smallexample
3309 The result is an efficient way of proceeding that
3310 correctly handles all the possible characters that could appear in the
3311 list of files to delete.  This is good news.  However, there is, as
3312 I'm sure you're expecting, also more bad news.  The problem is that
3313 this is not a portable construct; although other versions of Unix
3314 (notable BSD-derived ones) support @samp{-print0}, it's not
3315 universal.  So, is there a more universal mechanism?
3317 @subsection Going back to -exec
3319 There is indeed a more universal mechanism, which is a slight
3320 modification to the @samp{-exec} action.  The normal @samp{-exec}
3321 action assumes that the command to run is terminated with a semicolon
3322 (the semicolon normally has to be quoted in order to protect it from
3323 interpretation as the shell command separator).  The SVR4 edition of
3324 Unix introduced a slight variation, which involves terminating the
3325 command with @samp{+} instead:
3327 @smallexample
3328 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \+
3329 @end smallexample
3331 The above use of @samp{-exec} causes @code{find} to build up a long
3332 command line and then issue it.  This can be less efficient than some
3333 uses of @code{xargs}; for example @code{xargs} allows new command
3334 lines to be built up while the previous command is still executing, and
3335 allows you to specify a number of commands to run in parallel.
3336 However, the @code{find @dots{} -exec @dots{} +} construct has the advantage
3337 of wide portability.  GNU findutils did not support @samp{-exec @dots{} +}
3338 until version 4.2.12; one of the reasons for this is that it already
3339 had the @samp{-print0} action in any case.
3342 @subsection A more secure version of -exec
3344 The command above seems to be efficient and portable.  However,
3345 within it lurks a security problem.  The problem is shared with
3346 all the commands we've tried in this worked example so far, too.  The
3347 security problem is a race condition; that is, if it is possible for
3348 somebody to manipulate the filesystem that you are searching while you
3349 are searching it, it is possible for them to persuade your @code{find}
3350 command to cause the deletion of a file that you can delete but they
3351 normally cannot.  
3353 The problem occurs because the @samp{-exec} action is defined by the
3354 @acronym{POSIX} standard to invoke its command with the same working directory
3355 as @code{find} had when it was started.  This means that the arguments
3356 which replace the @{@} include a relative path from @code{find}'s
3357 starting point down the file that needs to be deleted.  For example,
3359 @smallexample
3360 find /var/tmp/stuff -mtime +90 -exec /bin/rm @{@} \+
3361 @end smallexample
3363 might actually issue the command:
3365 @smallexample
3366 /bin/rm /var/tmp/stuff/A /var/tmp/stuff/B /var/tmp/stuff/passwd
3367 @end smallexample
3369 Notice the file @file{/var/tmp/stuff/passwd}.  Likewise, the command:
3371 @smallexample
3372 cd /var/tmp && find stuff -mtime +90 -exec /bin/rm @{@} \+
3373 @end smallexample
3375 might actually issue the command:
3377 @smallexample
3378 /bin/rm stuff/A stuff/B stuff/passwd
3379 @end smallexample
3381 If an attacker can rename @file{stuff} to something else (making use
3382 of their write permissions in @file{/var/tmp}) they can replace it
3383 with a symbolic link to @file{/etc}.  That means that the
3384 @code{/bin/rm} command will be invoked on @file{/etc/passwd}.  If you
3385 are running your @code{find} command as root, the attacker has just managed
3386 to delete a vital file.  All they needed to do to achieve this was
3387 replace a subdirectory with a symbolic link at the vital moment.
3389 There is however, a simple solution to the problem.  This is an action
3390 which works a lot like @code{-exec} but doesn't need to traverse a
3391 chain of directories to reach the file that it needs to work on.  This
3392 is the @samp{-execdir} action, which was introduced by the BSD family
3393 of operating systems.   The command,
3395 @smallexample
3396 find /var/tmp/stuff -mtime +90 -execdir /bin/rm @{@} \+
3397 @end smallexample
3399 might delete a set of files by performing these actions:
3401 @enumerate
3402 @item 
3403 Change directory to /var/tmp/stuff/foo
3404 @item 
3405 Invoke @code{/bin/rm ./file1 ./file2 ./file3}
3406 @item
3407 Change directory to /var/tmp/stuff/bar
3408 @item 
3409 Invoke @code{/bin/rm ./file99 ./file100 ./file101}
3410 @end enumerate
3412 This is a much more secure method.  We are no longer exposed to a race
3413 condition.  For many typical uses of @code{find}, this is the best
3414 strategy.   It's reasonably efficient, but the length of the command
3415 line is limited not just by the operating system limits, but also by
3416 how many files we actually need to delete from each directory.
3418 Is it possible to do any better?   In the case of general file
3419 processing, no.  However, in the specific case of deleting files it is
3420 indeed possible to do better.  
3422 @subsection Using the -delete action
3424 The most efficient and secure method of solving this problem is to use
3425 the @samp{-delete} action:
3427 @smallexample
3428 find /var/tmp/stuff -mtime +90 -delete
3429 @end smallexample
3431 This alternative is more efficient than any of the @samp{-exec} or
3432 @samp{-execdir} actions, since it entirely avoids the overhead of
3433 forking a new process and using @code{exec} to run @code{/bin/rm}.  It
3434 is also normally more efficient than @code{xargs} for the same
3435 reason.   The file deletion is performed from the directory containing
3436 the entry to be deleted, so the @samp{-delete} action has the same
3437 security advantages as the @samp{-execdir} action has.  
3439 The @samp{-delete} action was introduced by the BSD family of
3440 operating systems.
3442 @subsection Improving things still further
3444 Is it possible to improve things still further?  Not without either
3445 modifying the system library to the operating system or having more specific
3446 knowledge of the layout of the filesystem and disk I/O subsystem, or
3447 both.
3449 The @code{find} command traverses the filesystem, reading
3450 directories.  It then issues a separate system call for each file to
3451 be deleted.  If we could modify the operating system, there are
3452 potential gains that could be made:
3454 @itemize
3455 @item
3456 We could have a system call to which we pass more than one filename
3457 for deletion
3458 @item
3459 Alternatively, we could pass in a list of inode numbers (on GNU/Linux
3460 systems, @code{readdir()} also returns the inode number of each
3461 directory entry) to be deleted.
3462 @end itemize
3464 The above possibilities sound interesting, but from the kernel's point
3465 of view it is difficult to enforce standard Unix access controls for
3466 such processing by inode number.  Such a facility would probably
3467 need to be restricted to the superuser.
3469 Another way of improving performance would be to increase the
3470 parallelism of the process.  For example if the directory hierarchy we
3471 are searching is actually spread across a number of disks, we might
3472 somehow be able to arrange for @code{find} to process each disk in
3473 parallel.  In practice GNU @code{find} doesn't have such an intimate
3474 understanding of the system's filesystem layout and disk I/O
3475 subsystem.
3477 However, since the system administrator can have such an understanding
3478 they can take advantage of it like so:
3480 @smallexample
3481 find /var/tmp/stuff1 -mtime +90 -delete &
3482 find /var/tmp/stuff2 -mtime +90 -delete &
3483 find /var/tmp/stuff3 -mtime +90 -delete &
3484 find /var/tmp/stuff4 -mtime +90 -delete &
3485 wait
3486 @end smallexample
3488 In the example above, four spearate instances of @code{find} are used
3489 to search four subdirectories in parallel.  The @code{wait} command
3490 simply waits for all of these to complete.  Whether this approach is
3491 more or less efficient than a single instance of @code{find} depends
3492 on a number of things:
3494 @itemize
3495 @item
3496 Are the directories being searched in parallel actually on separate
3497 disks?  If not, this parallel search might just result in a lot of
3498 disk head movement and so the speed might even be slower.
3499 @item
3500 Other activity - are other programs also doing things on those disks?
3501 @end itemize
3504 @subsection Conclusion
3506 The fastest and most secure way to delete files with the help of
3507 @code{find} is to use @samp{-delete}.  Using @code{xargs -0 -P N} can
3508 also make effective use of the disk, but it is not as secure.
3510 In the case where we're doing things other than deleting files, the
3511 most secure alternative is @samp{-execdir @dots{} +}, but this is not as
3512 portable as the insecure action @samp{-exec @dots{} +}.
3514 The @samp{-delete} action is not completely portable, but the only
3515 other possiblility which is as secure (@samp{-execdir}) is no more
3516 portable.  The most efficient portable alternative is @samp{-exec
3517 @dots{}+}, but this is insecure and isn't supported by versions of GNU
3518 findutils prior to 4.2.12.
3521 @node Updating A Timestamp File
3522 @section Updating A Timestamp File
3524 Suppose we have a directory full of files which is maintained with a
3525 set of automated tools; perhaps one set of tools updates them and
3526 another set of tools uses the result.  In this situation, it might be
3527 useful for the second set of tools to know if the files have recently
3528 been changed.  It might be useful, for example, to have a 'timestamp'
3529 file which gives the timestamp on the newest file in the collection.
3531 We can use @code{find} to achieve this, but there are several
3532 different ways to do it.
3534 @subsection Updating the Timestamp The Wrong Way
3536 The obvious but wrong answer is just to use @samp{-newer}:-
3538 @smallexample
3539 find subdir -newer timestamp -exec touch -r @{@} timestamp \; 
3540 @end smallexample
3542 This does the right sort of thing but has a bug.  Suppose that two
3543 files in the subdirectory have been updated, and that these are called
3544 @file{file1} and @file{file2}.  The command above will update
3545 @file{timestamp} with the modification time of @file{file1} or that of
3546 @file{file2}, but we don't know which one.  Since the timestamps on
3547 @file{file1} and @file{file2} will in general be different, this could
3548 well be the wrong value.
3550 One solution to this problem is to modify @code{find} to recheck the
3551 modification time of @file{timestamp} every time a file is to be
3552 compared against it, but that will reduce the performence of
3553 @code{find}.
3555 @subsection Using the test utlity to compare timestamps
3557 The @code{test} command can be used to compare timestamps:
3559 @smallexample
3560 find subdir -exec test @{@} -nt timestamp \; -exec touch -r @{@} timestamp \; 
3561 @end smallexample
3563 This will ensure that any changes made to the modification time of
3564 @file{timestamp} that take place during the execution of @code{find}
3565 are taken into account.  This resolves our earlier problem, but
3566 unfortunately this runs much more slowly.
3568 @subsection A combined approach
3570 We can of course still use @samp{-newer} to cut down on the number of
3571 calls to @code{test}:
3573 @smallexample
3574 find subdir -newer timestamp -a \
3575      -exec test @{@} -nt timestamp \; -a \
3576      -exec touch -r @{@} timestamp \; 
3577 @end smallexample
3579 Here, the @samp{-newer} test excludes all he files which are
3580 definitely older than the timestamp, but all the files which are newer
3581 than the old value of the timestamp are compared against the current
3582 updated timestamp.
3584 This is indeed faster in general, but the speed difference will depend
3585 on how many updated files there are.
3587 @subsection Using -printf and sort to compare timestamps
3589 It is possible to use the @samp{-printf} action to abandon the use of
3590 @code{test} entirely:
3592 @smallexample
3593 newest=$(find subdir -newer timestamp -printf "%A@:%p\n" | 
3594            sort -n | 
3595            tail -1 | 
3596            cut -d: -f2- ) 
3597 touch -r "$@{newest:-timestamp@}" timestamp
3598 @end smallexample
3600 The command above works by generating a list of the timestamps and
3601 names of all the files which are newer than the timestamp.  The
3602 @code{sort}, @code{tail} and @code{cut} comands simply pull out the
3603 name of the file with the largest timestamp value (that is, the latest
3604 file).  The @code{touch} command is then used to update the timestamp,
3606 The @code{"$@{newest:-timestamp@}"} expression simply expands to the
3607 value of @code{$newest} if that variable is set, but to
3608 @file{timestamp} otherwise.  This ensures that an argument is always
3609 given to the @samp{-r} option of the @code{touch} command.
3611 This approach seems quite efficient, but unfortunately it has a bug.
3612 Many operating systems now keep file modification time information at
3613 a granularity which is finer than one second.  Unfortunately the
3614 @samp{%A@@} format for @samp{-printf} only prints a whole-number value
3615 currently; that is, these values are at a one-second granularity.
3616 This means that in our example above, @samp{$newest} wil be the name
3617 of a file which is no more than one second older than the newest file,
3618 but may indeed be older.
3620 It would be possible to solve this problem with some kind of loop:
3622 @smallexample
3623 while true; do
3624         newest=$(find subdir -newer timestamp -printf "%A@@:%p\n" | 
3625            sort -n | 
3626            tail -1 | 
3627            cut -d: -f2- ) 
3628         if test -z "$newest" ; then
3629                 break
3630         else
3631                 touch -r "$newest" timestamp
3632         fi
3633 done
3634 @end smallexample
3636 A better fix for this problem would be to allow the @samp{%A@@} format
3637 to produce a result having a fractional part, too.  While this is
3638 planned for GNU @code{find}, it hasn't been done yet.
3640 @subsection Coping with sub-second timestamp resolution
3642 Another tool which often works with timestamps is @code{make}.  We can
3643 use @code{find} to generate a @file{Makefile} file on the fly and then
3644 use @code{make} to update the timestamps:
3646 @smallexample
3647 makefile=$(mktemp)
3648 find subdir \
3649         \( \! -xtype l \) \
3650         -newer timestamp \
3651         -printf "timestamp:: %p\n\ttouch -r %p timestamp\n\n" > "$makefile"
3652 make -f "$makefile"
3653 rm   -f "$makefile"
3654 @end smallexample
3656 Unfortunately although the solution above is quite elegant, it fails
3657 to cope with white space within file names, and adjusting it to do so
3658 would require a rather complex shell script.
3661 @subsection Coping with odd filenames too
3663 We can fix both of these problems (looping and problems with white
3664 space), and do things more efficiently too.  The following command
3665 works with newlines and doesn't need to sort the list of filenames.
3667 @smallexample
3668 find subdir -newer timestamp -printf "%A@@:%p\0" | 
3669    perl -0 newest.pl |
3670    xargs --no-run-if-empty --null -i \
3671       find @{@} -maxdepth 0 -newer timestamp -exec touch -r @{@} timestamp \;
3672 @end smallexample
3674 The first @code{find} command generates a list of files which are
3675 newer than the original timestamp file, and prints a list of them with
3676 their timestamps.  The @file{newest.pl} script simply filters out all
3677 the filenames which have timestamps which are older than whatever the
3678 newest file is:-
3680 @smallexample
3681 @verbatim
3682 #! /usr/bin/perl -0
3683 my @newest = ();
3684 my $latest_stamp = undef;
3685 while (<>) {
3686     my ($stamp, $name) = split(/:/);
3687     if (!defined($latest_stamp) || ($tstamp > $latest_stamp)) {
3688         $latest_stamp = $stamp;
3689         @newest = ();
3690     }
3691     if ($tstamp >= $latest_stamp) {
3692         push @newest, $name;
3693     }
3695 print join("\0", @newest);
3696 @end verbatim
3697 @end smallexample
3699 This prints a list of zero or more files, all of which are newer than
3700 the original timestamp file, and which have the same timestamp as each
3701 other, to the nearest second.  The second @code{find} command takes
3702 each resulting file one at a time, and if that is newer than the
3703 timestamp file, the timestamp is updated.
3705 @node Security Considerations, Error Messages, Worked Examples, Top
3706 @chapter Security Considerations
3708 Security considerations are important if you are using @code{find} or
3709 @code{xargs} to search for or process files that don't belong to you
3710 or which other people have control.  Security considerations
3711 relating to @code{locate} may also apply if you have files which you
3712 do not want others to see.
3714 The most severe forms of security problems affecting
3715 @code{find} and related programs are when third parties bring
3716 about a situation allowing them to do something
3717 they would normally not be able to accomplish.  This is called @emph{privilege
3718 elevation}.  This might include deleting files they would not normally
3719 be able to delete.  It is common for the operating system to periodically
3720 invoke @code{find} for self-maintenance purposes.  These invocations of
3721 @code{find} are particularly problematic from a security point of view
3722 as these are often invoked by the superuser and search the entire
3723 filesystem hierarchy.  Generally, the severity of any associated problem depends
3724 on what the system is going to do with the files found by @code{find}.
3726 @menu
3727 * Levels of Risk::      What is your level of exposure to security problems?
3728 * Security Considerations for find::  Security problems with find
3729 * Security Considerations for xargs:: Security problems with xargs
3730 * Security Considerations for locate:: Security problems with locate
3731 * Security Summary:: That was all very complex, what does it boil down to?
3732 @end menu
3735 @node Levels of Risk
3736 @section Levels of Risk
3738 There are some security risks inherent in the use of @code{find},
3739 @code{xargs} and (to a lesser extent) @code{locate}.  The severity of
3740 these risks depends on what sort of system you are using:
3742 @table @strong
3743 @item High risk
3744 Multi-user systems where you do not control (or trust) the other
3745 users, and on which you execute @code{find}, including areas where
3746 those other users can manipulate the filesystem (for example beneath
3747 @file{/home} or @file{/tmp}).
3749 @item Medium Risk
3750 Systems where the actions of other users can create file names chosen
3751 by them, but to which they don't have access while @code{find} is
3752 being run.  This access might include leaving programs running (shell
3753 background jobs, @code{at} or @code{cron} tasks, for example).  On
3754 these sorts of systems, carefully written commands (avoiding use of
3755 @samp{-print} for example) should not expose you to a high degree of
3756 risk.  Most systems fall into this category.
3758 @item Low Risk
3759 Systems to which untrusted parties do not have access, cannot create
3760 file names of their own choice (even remotely) and which contain no
3761 security flaws which might enable an untrusted third party to gain
3762 access.  Most systems do not fall into this category because there are
3763 many ways in which external parties can affect the names of files that
3764 are created on your system.  The system on which I am writing this for
3765 example automatically downloads software updates from the Internet;
3766 the names of the files in which these updates exist are chosen by
3767 third parties@footnote{Of course, I trust these parties to a large
3768 extent anyway, because I install software provided by them; I choose
3769 to trust them in this way, and that's a deliberate choice}.
3770 @end table
3772 In the discussion above, ``risk'' denotes the likelihood that someone
3773 can cause @code{find}, @code{xargs}, @code{locate} or some other
3774 program which is controlled by them to do something you did not
3775 intend.  The levels of risk suggested do not take any account of the
3776 consequences of this sort of event.  That is, if you operate a ``low
3777 risk'' type system, but the consequences of a security problem are
3778 disastrous, then you should still give serious thought to all the
3779 possible security problems, many of which of course will not be
3780 discussed here -- this section of the manual is intended to be
3781 informative but not comprehensive or exhaustive.
3783 If you are responsible for the operation of a system where the
3784 consequences of a security problem could be very important, you should
3785 do two things:-
3787 @enumerate
3788 @item Define a security policy which defines who is allowed to do what
3789 on your system.
3790 @item Seek competent advice on how to enforce your policy, detect
3791 breaches of that policy, and take account of any potential problems
3792 that might fall outside the scope of your policy.
3793 @end enumerate
3796 @node Security Considerations for find
3797 @section Security Considerations for @code{find}
3800 Some of the actions @code{find} might take have a direct effect;
3801 these include @code{-exec} and @code{-delete}.  However, it is also
3802 common to use @code{-print} explicitly or implicitly, and so if
3803 @code{find} produces the wrong list of file names, that can also be a
3804 security problem; consider the case for example where @code{find} is
3805 producing a list of files to be deleted.
3807 We normally assume that the @code{find} command line expresses the
3808 file selection criteria and actions that the user had in mind -- that
3809 is, the command line is ``trusted'' data.
3811 From a security analysis point of view, the output of @code{find}
3812 should be correct; that is, the output should contain only the names
3813 of those files which meet the user's criteria specified on the command
3814 line.  This applies for the @code{-exec} and @code{-delete} actions;
3815 one can consider these to be part of the output.
3817 On the other hand, the contents of the filesystem can be manipulated
3818 by other people, and hence we regard this as ``untrusted'' data.  This
3819 implies that the @code{find} command line is a filter which converts
3820 the untrusted contents of the filesystem into a correct list of output
3821 files.
3823 The filesystem will in general change while @code{find} is searching
3824 it; in fact, most of the potential security problems with @code{find}
3825 relate to this issue in some way.
3827 @dfn{Race conditions} are a general class of security problem where the
3828 relative ordering of actions taken by @code{find} (for example) and
3829 something else are critically important in getting the correct and expected result@footnote{This is more or less the
3830 definition of the term ``race condition''} .
3832 For @code{find}, an attacker might move or rename files or directories in
3833 the hope that an action might be taken against a file which was not
3834 normally intended to be affected.  Alternatively, this sort of attack
3835 might be intended to persuade @code{find} to search part of the
3836 filesystem which would not normally be included in the search
3837 (defeating the @code{-prune} action for example).
3839 @menu
3840 * Changing the Current Working Directory::
3841 * Race Conditions with -exec::
3842 * Race Conditions with -print and -print0::
3843 @end menu
3846 @node Changing the Current Working Directory
3847 @subsection Changing the Current Working Directory
3849 As @code{find} searches the filesystem, it finds subdirectories and
3850 then searches within them by changing its working directory.  First,
3851 @code{find} reaches and recognizes a subdirectory.  It then decides if that
3852 subdirectory meets the criteria for being searched; that is, any
3853 @samp{-xdev} or @samp{-prune} expressions are taken into account.  The
3854 @code{find} program will then change working directory and proceed to
3855 search the directory.
3857 A race condition attack might take the form that once the checks
3858 relevant to @samp{-xdev} and @samp{-prune} have been done, an attacker
3859 might rename the directory that was being considered, and put in its
3860 place a symbolic link that actually points somewhere else.
3862 The idea behind this attack is to fool @code{find} into going into the
3863 wrong directory.  This would leave @code{find} with a working
3864 directory chosen by an attacker, bypassing any protection apparently
3865 provided by @samp{-xdev} and @samp{-prune}, and any protection
3866 provided by being able to @emph{not} list particular directories on
3867 the @code{find} command line.  This form of attack is particularly
3868 problematic if the attacker can predict when the @code{find} command
3869 will be run, as is the case with @code{cron} tasks for example.
3871 GNU @code{find} has specific safeguards to prevent this general class
3872 of problem.  The exact form of these safeguards depends on the
3873 properties of your system.
3875 @menu
3876 * O_NOFOLLOW::                     Safely changing directory using fchdir().
3877 * Systems without O_NOFOLLOW::     Checking for symbolic links after chdir().
3878 * Working with automounters::      These can look like race condition exploits
3879 * Problems with dead NFS servers:: If you don't have O_NOFOLLOW, this is a problem.
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 not, an
3930 error message is issued and @code{find} exits immediately.  This
3931 method prevents filesystem manipulation attacks from persuading
3932 @code{find} to search parts of the filesystem it did not intend.
3933 However, we have to take special steps in order to avoid mistakenly
3934 concluding that there is a problem with any ``automount'' mount
3935 points.
3937 @node Working with automounters
3938 @subsubsection Working with automounters
3940 Where a filesystem ``automounter'' is in use it can be the case that the use of the
3941 @code{chdir()} system call can itself cause a new filesystem to be
3942 mounted at that point.  On systems that do not support O_NOFOLLOW,
3943 this will cause @code{find}'s security check to fail.
3945 However, this does not normally represent a security problem, since
3946 the automounter configuration is normally set up by the system
3947 administrator.  Therefore, if the @code{chdir()} sanity check fails,
3948 @code{find} will check to see if a new filesystem has been mounted at
3949 the current directory; if so, @code{find} will issue a warning message
3950 and continue.
3952 To make this solution work, @code{find} reads the list of mounted
3953 filesystems at startup, and again when the sanity check fails.  It
3954 compares the two lists to find out if the directory it has moved into
3955 has just been mounted.
3957 @node Problems with dead NFS servers
3958 @subsubsection Problems with dead NFS servers
3960 Examining every mount point on the system has a downside too.  In
3961 general, @code{find} will be used to search just part of the
3962 filesystem.  However, @code{find} examines every mount point.  If the
3963 system has a filesystem mounted on an unresponsive NFS server,
3964 @code{find} will hang, waiting for the NFS server to respond.  Worse,
3965 it does this even if the affected mount point is not within the
3966 directory tree that @code{find} would have searched anyway.
3968 This is very unfortunate.  However, this problem only affects systems
3969 that have no support for O_NOFOLLOW.  As far as I can tell, it is not
3970 possible on such systems to fix all three problems (the race
3971 condition, the false-alarm at automount mount points, and the hang at
3972 startup if there is a dead NFS server) at once.  If you have some
3973 ideas about how @code{find} could do this better, please send email to
3974 the @email{bug-findutils@@gnu.org} mailing list.
3976 @node Race Conditions with -exec
3977 @subsection Race Conditions with -exec
3979 The @samp{-exec} action causes another program to be run.  It passes
3980 to the program the name of the file which is being considered at the
3981 time.  The invoked program will typically then perform some action
3982 on that file.  Once again, there is a race condition which can be
3983 exploited here.  We shall take as a specific example the command
3985 @example
3986 find /tmp -path /tmp/umsp/passwd -exec /bin/rm
3987 @end example
3989 In this simple example, we are identifying just one file to be deleted
3990 and invoking @code{/bin/rm} to delete it.  A problem exists because
3991 there is a time gap between the point where @code{find} decides that
3992 it needs to process the @samp{-exec} action and the point where the
3993 @code{/bin/rm} command actually issues the @code{unlink()} system
3994 call to delete the file from the filesystem.  Within this time period, an attacker can rename the
3995 @file{/tmp/umsp} directory, replacing it with a symbolic link to
3996 @file{/etc}.  There is no way for @code{/bin/rm} to determine that it
3997 is working on the same file that @code{find} had in mind.  Once the
3998 symbolic link is in place, the attacker has persuaded @code{find} to
3999 cause the deletion of the @file{/etc/passwd} file, which is not the
4000 effect intended by the command which was actually invoked.
4002 One possible defence against this type of attack is to modify the
4003 behaviour of @samp{-exec} so that the @code{/bin/rm} command is run
4004 with the argument @file{./passwd} and a suitable choice of working
4005 directory.  This would allow the normal sanity check that @code{find}
4006 performs to protect against this form of attack too.  Unfortunately,
4007 this strategy cannot be used as the POSIX standard specifies that the
4008 current working directory for commands invoked with @samp{-exec} must
4009 be the same as the current working directory from which @code{find}
4010 was invoked.  This means that the @samp{-exec} action is inherently
4011 insecure and can't be fixed.
4013 GNU @code{find} implements a more secure variant of the @samp{-exec}
4014 action, @samp{-execdir}.  The @samp{-execdir} action
4015 ensures that it is not necessary to dereference subdirectories to
4016 process target files.  The current directory used to invoke programs
4017 is the same as the directory in which the file to be processed exists
4018 (@file{/tmp/umsp} in our example, and only the basename of the file to
4019 be processed is passed to the invoked command, with a @samp{./}
4020 prepended (giving @file{./passwd} in our example).
4022 The @samp{-execdir} action refuses to do anything if the current
4023 directory is included in the @var{$PATH} environment variable.  This
4024 is necessary because @samp{-execdir} runs programs in the same
4025 directory in which it finds files -- in general, such a directory
4026 might be writable by untrusted users.  For similar reasons,
4027 @samp{-execdir} does not allow @samp{@{@}} to appear in the name of
4028 the command to be run.
4030 @node Race Conditions with -print and -print0
4031 @subsection Race Conditions with -print and -print0
4033 The @samp{-print} and @samp{-print0} actions can be used to produce a
4034 list of files matching some criteria, which can then be used with some
4035 other command, perhaps with @code{xargs}.  Unfortunately, this means
4036 that there is an unavoidable time gap between @code{find} deciding
4037 that one or more files meet its criteria and the relevant command
4038 being executed.  For this reason, the @samp{-print} and @samp{-print0}
4039 actions are just as insecure as @samp{-exec}.
4041 In fact, since the construction
4043 @example
4044 find @dots{}  -print | xargs @enddots{}
4045 @end example
4047 does not cope correctly with newlines or other ``white space'' in
4048 file names, and copes poorly with file names containing quotes, the
4049 @samp{-print} action is less secure even than @samp{-print0}.
4052 @comment  node-name,  next,  previous,  up
4053 @comment @node Security Considerations for xargs
4054 @node Security Considerations for xargs
4055 @section Security Considerations for @code{xargs}
4057 The description of the race conditions affecting the @samp{-print}
4058 action of @code{find} shows that @code{xargs} cannot be secure if it
4059 is possible for an attacker to modify a filesystem after @code{find}
4060 has started but before @code{xargs} has completed all its actions.
4062 However, there are other security issues that exist even if it is not
4063 possible for an attacker to have access to the filesystem in real
4064 time.  Firstly, if it is possible for an attacker to create files with
4065 names of their choice on the filesystem, then @code{xargs} is
4066 insecure unless the @samp{-0} option is used.  If a file with the name
4067 @file{/home/someuser/foo/bar\n/etc/passwd} exists (assume that
4068 @samp{\n} stands for a newline character), then @code{find @dots{} -print}
4069 can be persuaded to print three separate lines:
4071 @example
4072 /home/someuser/foo/bar
4074 /etc/passwd
4075 @end example
4077 If it finds a blank line in the input, @code{xargs} will ignore it.
4078 Therefore, if some action is to be taken on the basis of this list of
4079 files, the @file{/etc/passwd} file would be included even if this was
4080 not the intent of the person running find.  There are circumstances in
4081 which an attacker can use this to their advantage.  The same
4082 consideration applies to file names containing ordinary spaces rather
4083 than newlines, except that of course the list of file names will no
4084 longer contain an ``extra'' newline.
4086 This problem is an unavoidable consequence of the default behaviour of
4087 the @code{xargs} command, which is specified by the POSIX standard.
4088 The only ways to avoid this problem are either to avoid all use of
4089 @code{xargs} in favour for example of @samp{find -exec} or (where
4090 available) @samp{find -execdir}, or to use the @samp{-0} option, which
4091 ensures that @code{xargs} considers file names to be separated by
4092 ASCII NUL characters rather than whitespace.  However, useful as this
4093 option is, the POSIX standard does not make it mandatory.
4095 @comment  node-name,  next,  previous,  up
4096 @node Security Considerations for locate
4097 @section Security Considerations for @code{locate}
4099 It is fairly unusual for the output of @code{locate} to be fed into
4100 another command.  However, if this were to be done, this would raise
4101 the same set of security issues as the use of @samp{find @dots{} -print}.
4102 Although the problems relating to whitespace in file names can be
4103 resolved by using @code{locate}'s @samp{-0} option, this still leaves
4104 the race condition problems associated with @samp{find @dots{} -print0}.
4105 There is no way to avoid these problems in the case of @code{locate}.
4107 @node Security Summary
4108 @section Summary
4110 Where untrusted parties can create files on the system, or affect the
4111 names of files that are created, all uses for @code{find},
4112 @code{locate} and @code{xargs} have known security problems except the
4113 following:
4115 @table @asis
4116 @item Informational use only
4117 Uses where the programs are used to prepare lists of file names upon
4118 which no further action will ever be taken.
4120 @item @samp{-delete}
4121 Use of the @samp{-delete} action with @code{find} to delete files
4122 which meet specified criteria
4124 @item @samp{-execdir}
4125 Use of the @samp{-execdir} action with @code{find} where the
4126 @env{PATH} environment variable contains directories which contain
4127 only trusted programs.
4128 @end table
4130 @comment  node-name,  next,  previous,  up
4131 @node Error Messages, Primary Index, Security Considerations, Top
4132 @chapter Error Messages
4134 This section describes some of the error messages sometimes made by
4135 @code{find}, @code{xargs}, or @code{locate}, explains them and in some
4136 cases provides advice as to what you should do about this.
4138 This manual is written in English.  The GNU findutils software
4139 features translations of error messages for many languages.  For this
4140 reason the error messages produced by
4141 the programs are made to be as self-explanatory as possible.  This approach avoids leaving people to
4142 figure out which test an English-language error message
4143 corresponds to. Error messages which are self-explanatory
4144 will not normally be mentioned in this document.  For
4145 those messages mentioned in this document, only the
4146 English-language version of the message will be listed.
4148 @menu
4149 * Error Messages From find::
4150 * Error Messages From xargs::
4151 * Error Messages From locate::
4152 * Error Messages From updatedb::
4153 @end menu
4155 @node Error Messages From find, Error Messages From xargs, , Error Messages
4156 @section Error Messages From @code{find}
4158 @table @samp
4159 @item invalid predicate `-foo'
4160 This means that the @code{find} command line included something that
4161 started with a dash or other special character.  The @code{find}
4162 program tried to interpret this as a test, action or option, but
4163 didn't recognise it.  If it was intended to be a test, check what was
4164 specified against the documentation.  If, on the other hand, the
4165 string is the name of a file which has been expanded from a wildcard
4166 (for example because you have a @samp{*} on the command line),
4167 consider using @samp{./*} or just @samp{.} instead.
4169 @item unexpected extra predicate
4170 This usually happens if you have an extra bracket on the command line
4171 (for example @samp{find . -print \)}).
4173 @item Warning: filesystem /path/foo has recently been mounted
4174 @itemx Warning: filesystem /path/foo has recently been unmounted
4175 These messages might appear when @code{find} moves into a directory
4176 and finds that the device number and inode are different to what it
4177 expected them to be.  If the directory @code{find} has moved into is
4178 on an network filesystem (NFS), it will not issue this message, because
4179 @code{automount} frequently mounts new filesystems on directories as
4180 you move into them (that is how it knows you want to use the
4181 filesystem).  So, if you do see this message, be wary ---
4182 @code{automount} may not have been responsible.  Consider the
4183 possibility that someone else is manipulating the filesystem while
4184 @code{find} is running.  Some people might do this in order to mislead
4185 @code{find} or persuade it to look at one set of files when it thought
4186 it was looking at another set.
4188 @item /path/foo changed during execution of find (old device number 12345, new device number 6789, filesystem type is <whatever>) [ref XXX]
4189 This message is issued when @code{find} moves into a directory and ends up
4190 somewhere it didn't expect to be.  This happens in one of two
4191 circumstances.  Firstly, this happens when @code{automount} intervenes
4192 on a system where @code{find} doesn't know how to determine what
4193 the current set of mounted filesystems is.
4195 Secondly, this can happen when the device number of a directory
4196 appears to change during a change of current directory, but
4197 @code{find} is moving up the filesystem hierarchy rather than down into it.
4198 In order to prevent @code{find} wandering off into some unexpected
4199 part of the filesystem, we stop it at this point.
4201 @item Don't know how to use getmntent() to read `/etc/mtab'.  This is a bug.
4202 This message is issued when a problem similar to the above occurs on a
4203 system where @code{find} doesn't know how to figure out the current
4204 list of mount points.  Ask for help on @email{bug-findutils@@gnu.org}.
4206 @item /path/foo/bar changed during execution of find (old inode number 12345, new inode number 67893, filesystem type is <whatever>) [ref XXX]"),
4207 This message is issued when @code{find} moves into a directory and
4208 discovers that the inode number of that directory
4209 is different from the inode number that it obtained when it examined the
4210 directory previously.  This usually means that while
4211 @code{find} was deep in a directory hierarchy doing a
4212 time consuming operation, somebody has moved one of the parent directories to
4213 another location in the same filesystem.  This may or may not have been done
4214 maliciously.  In any case, @code{find} stops at this point
4215 to avoid traversing parts of the filesystem that it wasn't
4216 intended.  You can use @code{ls -li} or @code{find /path -inum
4217 12345 -o -inum 67893} to find out more about what has happened.
4219 @item sanity check of the fnmatch() library function failed.
4220 Please submit a bug report.  You may well be asked questions about
4221 your system, and if you compiled the @code{findutils} code yourself,
4222 you should keep your copy of the build tree around.  The likely
4223 explanation is that your system has a buggy implementation of
4224 @code{fnmatch} that looks enough like the GNU version to fool
4225 @code{configure}, but which doesn't work properly.
4227 @item cannot fork
4228 This normally happens if you use the @code{-exec} action or
4229 something similar (@code{-ok} and so forth) but the system has run out
4230 of free process slots.  This is either because the system is very busy
4231 and the system has reached its maximum process limit, or because you
4232 have a resource limit in place and you've reached it.  Check the
4233 system for runaway processes (with @code{ps}, if possible).  Some process
4234 slots are normally reserved for use by @samp{root}.
4236 @item some-program terminated by signal 99
4237 Some program which was launched with @code{-exec} or similar was killed
4238 with a fatal signal.  This is just an advisory message.
4239 @end table
4242 @node Error Messages From xargs, Error Messages From locate, Error Messages From find, Error Messages
4243 @section Error Messages From xargs
4245 @table @samp
4246 @item environment is too large for exec
4247 This message means that you have so many environment variables set (or
4248 such large values for them) that there is no room within the
4249 system-imposed limits on program command line argument length to
4250 invoke any program.  This is an unlikely situation and is more likely
4251 result of an attempt to test the limits of @code{xargs}, or break it.
4252 Please try unsetting some environment variables, or exiting the
4253 current shell.
4255 @item can not fit single argument within argument list size limit
4256 You are using the @samp{-I} option and @code{xargs} doesn't have
4257 enough space to build a command line because it has read a really
4258 large item and it doesn't fit.  You can probably work around this
4259 problem with the @samp{-s} option, but the default size is pretty
4260 large.  This is a rare situation and is more likely an attempt to test
4261 the limits of @code{xargs}, or break it.  Otherwise, you will need to
4262 try to shorten the problematic argument or not use @code{xargs}.
4264 @item cannot fork
4265 See the description of the similar message for @code{find}.
4267 @item <program>: exited with status 255; aborting
4268 When a command run by @code{xargs} exits with status 255, @code{xargs}
4269 is supposed to stop.  If this is not what you intended, wrap the
4270 program you are trying to invoke in a shell script which doesn't
4271 return status 255.
4273 @item <program>: terminated by signal 99
4274 See the description of the similar message for @code{find}.
4275 @end table
4277 @node Error Messages From locate, Error Messages From updatedb, Error Messages From xargs, Error Messages
4278 @section Error Messages From @code{locate}
4280 @table @samp
4281 @item warning: database `/usr/local/var/locatedb' is more than 8 days old
4282 The @code{locate} program relies on a database which is periodically
4283 built by the @code{updatedb} program.  That hasn't happened in a long
4284 time.  To fix this problem, run @code{updatedb} manually.  This can
4285 often happen on systems that are generally not left on, so the
4286 periodic ``cron'' task which normally does this doesn't get a chance
4287 to run.
4289 @item locate database `/usr/local/var/locatedb' is corrupt or invalid
4290 This should not happen.  Re-run @code{updatedb}.  If that works, but
4291 @code{locate} still produces this error, run @code{locate --version}
4292 and @code{updatedb --version}.  These should produce the same output.
4293 If not, you are using a mixed toolset; check your @samp{$PATH}
4294 environment variable and your shell aliases (if you have any).  If
4295 both programs claim to be GNU versions, this is a bug; all versions of
4296 these programs should interoperate without problem.  Ask for help on
4297 @email{bug-findutils@@gnu.org}.
4298 @end table
4301 @node Error Messages From updatedb, , Error Messages From locate, Error Messages
4302 @section Error Messages From updatedb
4304 The @code{updatedb} program (and the programs it invokes) do issue
4305 error messages, but none seem to be candidates for guidance.  If
4306 you are having a problem understanding one of these, ask for help on
4307 @email{bug-findutils@@gnu.org}.
4309 @node Primary Index, , Error Messages, Top
4310 @unnumbered @code{find} Primary Index
4312 This is a list of all of the primaries (tests, actions, and options)
4313 that make up @code{find} expressions for selecting files.  @xref{find
4314 Expressions}, for more information on expressions.
4316 @printindex fn
4318 @bye
4320 @comment texi related words used by Emacs' spell checker ispell.el
4322 @comment LocalWords: texinfo setfilename settitle setchapternewpage
4323 @comment LocalWords: iftex finalout ifinfo DIR titlepage vskip pt
4324 @comment LocalWords: filll dir samp dfn noindent xref pxref
4325 @comment LocalWords: var deffn texi deffnx itemx emph asis
4326 @comment LocalWords: findex smallexample subsubsection cindex
4327 @comment LocalWords: dircategory direntry itemize
4329 @comment other words used by Emacs' spell checker ispell.el
4330 @comment LocalWords: README fred updatedb xargs Plett Rendell akefile
4331 @comment LocalWords: args grep Filesystems fo foo fOo wildcards iname
4332 @comment LocalWords: ipath regex iregex expr fubar regexps
4333 @comment LocalWords: metacharacters macs sr sc inode lname ilname
4334 @comment LocalWords: sysdep noleaf ls inum xdev filesystems usr atime
4335 @comment LocalWords: ctime mtime amin cmin mmin al daystart Sladkey rm
4336 @comment LocalWords: anewer cnewer bckw rf xtype uname gname uid gid
4337 @comment LocalWords: nouser nogroup chown chgrp perm ch maxdepth
4338 @comment LocalWords: mindepth cpio src CD AFS statted stat fstype ufs
4339 @comment LocalWords: nfs tmp mfs printf fprint dils rw djm Nov lwall
4340 @comment LocalWords: POSIXLY fls fprintf strftime locale's EDT GMT AP
4341 @comment LocalWords: EST diff perl backquotes sprintf Falstad Oct cron
4342 @comment LocalWords: eg vmunix mkdir afs allexec allwrite ARG bigram
4343 @comment LocalWords: bigrams cd chmod comp crc CVS dbfile dum eof
4344 @comment LocalWords: fileserver filesystem fn frcode Ghazi Hnewc iXX
4345 @comment LocalWords: joeuser Kaveh localpaths localuser LOGNAME
4346 @comment LocalWords: Meyering mv netpaths netuser nonblank nonblanks
4347 @comment LocalWords: ois ok Pinard printindex proc procs prunefs
4348 @comment LocalWords: prunepaths pwd RFS rmadillo rmdir rsh sbins str
4349 @comment LocalWords: su Timar ubins ug unstripped vf VM Weitzel
4350 @comment LocalWords: wildcard zlogout basename execdir wholename iwholename
4351 @comment LocalWords: timestamp timestamps Solaris FreeBSD OpenBSD POSIX