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