title: GNU Findutils

1 Introduction

This manual shows how to find files that meet criteria you specify, and how to perform various actions on the files that you find.

The principal programs that you use to perform these tasks are find, locate, and xargs.

Some of the examples in this manual use capabilities specific to the GNU versions of those programs.

GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood.

GNU xargs was originally written by Mike Rendell, with enhancements by David MacKenzie.

GNU locate and its associated utilities were originally written by James Woods, with enhancements by David MacKenzie.

The idea for find -print0 and xargs -0 came from Dan Bernstein.

The current maintainer of GNU findutils (and this manual) is James Youngman.

Many other people have contributed bug fixes, small improvements, and helpful suggestions. Thanks!

1.1 Scope

For brevity, the word file in this manual means a regular file, a directory, a symbolic link, or any other kind of node that has a directory entry.

A directory entry is also called a file name.

A file name may contain some, all, or none of the directories in a path that leads to the file.

These are all examples of what this manual calls file names:

   parser.c
  README
  ./budget/may-94.sc
  fred/.cshrc
  /usr/local/include/termcap.h

A directory tree is a directory and the files it contains, all of its subdirectories and the files they contain, etc.

It can also be a single non-directory file.

These programs enable you to find the files in one or more directory trees that:

  • have names that contain certain text or match a certain pattern;
  • are links to certain files;
  • were last used during a certain period of time;
  • are within a certain size range;
  • are of a certain type (regular file, directory, symbolic link, etc.);
  • are owned by a certain user or group;
  • have certain access permissions or special mode bits;
  • contain text that matches a certain pattern;
  • are within a certain depth in the directory tree;
  • or some combination of the above.

Once you have found the files you’re looking for (or files that are potentially the ones you’re looking for), you can do more to them than simply list their names.

You can get any combination of the files’attributes, or process the files in many ways, either individually or in groups of various sizes.


Actions that you might want to perform on the files you have found include, but are not limited to:

  • view or edit
  • store in an archive
  • remove or rename
  • change access permissions
  • classify into groups

This manual describes how to perform each of those tasks, and more.

1.2 Overview

The principal programs used for making lists of files that match given criteria and running commands on them are find, locate, and xargs.

An additional command, updatedb, is used by system administrators to create databases for locate to use.

find [FILE...] [EXPRESSION]

find searches for files in a directory hierarchy and prints information about the files it found. It is run like this:

Here is a typical use of find. This example prints the names of all files in the directory tree rooted in /usr/src whose name ends with .c and that are larger than 100 KiB.

find /usr/src -name '*.c' -size +100k -print

Notice that the wildcard must be enclosed in quotes in order to protect it from expansion by the shell.

2 Finding Files

By default, find prints to the standard output the names of the files that match the given criteria. *Note Actions::, for how to get more information about the matching files.

2.1 ‘find’ Expressions

The expression that find uses to select files consists of one or more “primaries”, each of which is a separate command line argument to find. find evaluates the expression each time it processes a file.

An expression can contain any of the following types of primaries:

Option

affect overall operation rather than the processing of a specific file;

Test

return a true or false value, depending on the file’s attributes;

Action

have side effects and return a true or false value;

Operators

connect the other arguments and affect when and whether they are evaluated.

You can omit the operator between two primaries; it defaults to -and. *Note Combining Primaries With Operators::, for ways to connect primaries into more complex expressions.

The -print action is performed on all files for which the entire expression is true (*note Print File Name::), unless the expression contains an action other than -prune or -quit.

Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf.

Options take effect immediately, rather than being evaluated for each file when their place in the expression is reached.

Therefore, for clarity, it is best to place them at the beginning of the expression.

There are two exceptions to this; -daystart and -follow have different effects depending on where in the command line they appear.

This can be confusing, so it’s best to keep them at the beginning, too.

Many of the primaries take arguments, which immediately follow them in the next command line argument to find.

Some arguments are file names, patterns, or other strings; others are numbers.

Numeric arguments can be specified as

+N

for greater than N,

-N

for less than N,

N

for exactly N.

2.2 Starting points

GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of operator precedence, until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name.

If no starting-point is specified, the current directory . is assumed.

A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the list of starting point arguments: it does that by reading until an expression argument comes (which also starts with a -).

Now, if a starting point argument would begin with a -, then find would treat it as expression argument instead.

Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either ./, or to use absolute path names starting with /.

Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find.

-files0-from file

Read the starting points from ‘file’ instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to ‘find’. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time.

The ‘file’ argument is mandatory. One can use ‘-files0-from -’ to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions ‘-ok’ and ‘-okdir’ are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation.

The starting points in ‘file’ have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non-Zero exit code later.

In the case the given ‘file’ is empty, ‘find’ does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where ‘find’ assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. ‘find’ will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass ‘-maxdepth 0’.

Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By “unspecified” here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release.

Example: Given that another program ‘proggy’ pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them:

proggy | find -files0-from - -maxdepth 0 -type f -empty

The use of ‘-files0-from -’ means to read the names of the starting points from standard input, i.e., from the pipe; and ‘-maxdepth 0’ ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one).

2.3 Name

Here are ways to search for files whose name matches a certain pattern. *Note Shell Pattern Matching::, for a description of the PATTERN arguments to these tests.

Each of these tests has a case-sensitive version and a case-insensitive version, whose name begins with i. In a case-insensitive comparison, the patterns fo* and F?? match the file names Foo, FOO, foo, fOo, etc.

2.3.1 Base Name Patterns

Test: -name pattern

True if the base of the file name (the path with the leading directories removed) matches shell pattern PATTERN.

Test: -iname pattern

True if the base of the file name (the path with the leading directories removed) matches shell pattern PATTERN, match is case-insensitive.

Option: -prune

To ignore a whole directory tree, use ‘-prune’ (*note Directories::).

As an example, to find Texinfo source files in ‘/usr/local/doc’:

find /usr/local/doc -name '*.texi'

Notice that the wildcard must be enclosed in quotes in order to protect it from expansion by the shell.

As of findutils version 4.2.2, patterns for ‘-name’ and ‘-iname’ match a file name with a leading ’.‘.

For example the command

find /tmp -name \*bar match the file /tmp/.foobar.

Braces within the pattern ({}) are not considered to be special (that is, find . -name 'foo{1,2}' matches a file named foo{1,2}, not the files foo1 and foo2.

Because the leading directories are removed, the file names considered for a match with -name will never include a slash, so -name a/b will never match anything (you probably need to use -path instead).

Footnotes (1) Because we need to perform case-insensitive matching, the GNU fnmatch implementation is always used; if the C library includes the GNU implementation, we use that and otherwise we use the one from gnulib

2.3.2 Full Name Patterns

— Test: -path pattern — Test: -wholename pattern True if the entire file name, starting with the command line argument under which the file was found, matches shell pattern PATTERN. To ignore a whole directory tree, use ‘-prune’ rather than checking every file in the tree (*note Directories::). The “entire file name” as used by ‘find’ starts with the starting-point specified on the command line, and is not converted to an absolute pathname, so for example ‘cd /; find tmp -wholename /tmp’ will never match anything. Find compares the ‘-path’ argument with the concatenation of a directory name and the base name of the file it’s considering. Since the concatenation will never end with a slash, ‘-path’ arguments ending in ’/’ will match nothing (except perhaps a start point specified on the command line). The name ‘-wholename’ is GNU-specific, but ‘-path’ is more portable; it is supported by HP-UX ‘find’ and is part of the POSIX 2008 standard.

— Test: -ipath pattern — Test: -iwholename pattern These tests are like ‘-wholename’ and ‘-path’, but the match is case-insensitive.

In the context of the tests ‘-path’, ‘-wholename’, ‘-ipath’ and ‘-iwholename’, a “full path” is the name of all the directories traversed from ‘find”s start point to the file being tested, followed by the base name of the file itself.

These paths are often not absolute paths; for example

cd /tmp
mkdir -p foo/bar/baz
find foo -path foo/bar -print
## вывод
foo/bar
find foo -path /tmp/foo/bar -print
find /tmp/foo -path /tmp/foo/bar -print
## вывод
/tmp/foo/bar

Notice that the second find command prints nothing, even though /tmp/foo/bar exists and was examined by find.

Unlike file name expansion on the command line, a * in the pattern will match both / and leading dots in file names:

find .  -path '*f'
## вывод
./quux/bar/baz/f
find .  -path '*/*config'
## вывод
./quux/bar/baz/.config

Test: -regex expr

True if the entire file name matches regular expression EXPR. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression .*bar. or .*b.*3, but not f.*r3. *Note Syntax of Regular Expressions: (emacs)Regexps, for a description of the syntax of regular expressions. For -iregex, the match is case-insensitive. As for -path, the candidate file name never ends with a slash, so regular expressions which only match something that ends in slash will always fail. There are several varieties of regular expressions; by default this test uses POSIX basic regular expressions, but this can be changed with the option -regextype.

Test: -iregex expr

Same as -regex, but match is case insensitive.

Option

-regextype name

This option controls the variety of regular expression syntax understood by the ‘-regex’ and ‘-iregex’ tests. This option is positional; that is, it only affects regular expressions which occur later in the command line. If this option is not given, GNU Emacs regular expressions are assumed. Currently-implemented types are

  • emacs Regular expressions compatible with GNU Emacs; this is also the default behaviour if this option is not used.
  • posix-awk Regular expressions compatible with the POSIX awk command (not GNU awk)
  • posix-basic POSIX Basic Regular Expressions.
  • posix-egrep Regular expressions compatible with the POSIX egrep command
  • posix-extended POSIX Extended Regular Expressions

*note Regular Expressions: for more information on the regular expression dialects understood by GNU findutils.

To search for files by name without having to actually scan the directories on the disk (which can be slow), you can use the ‘locate’ program. For each shell pattern you give it, ‘locate’ searches one or more databases of file names and displays the file names that contain the pattern. *Note Shell Pattern Matching::, for details about shell patterns.

If a pattern is a plain string - it contains no metacharacters - ‘locate’ displays all file names in the database that contain that string. If a pattern contains metacharacters, ‘locate’ only displays file names that match the pattern exactly. As a result, patterns that contain metacharacters should usually begin with a ’*’, and will most often end with one as well. The exceptions are patterns that are intended to explicitly match the beginning or end of a file name. If you only want ‘locate’ to match against the last component of the file names (the “base name” of the files) you can use the ‘—basename’ option. The opposite behaviour is the default, but can be selected explicitly by using the option ‘—wholename’. The command locate PATTERN is almost equivalent to find DIRECTORIES -name PATTERN where DIRECTORIES are the directories for which the file name databases contain information. The differences are that the ‘locate’ information might be out of date, and that ‘locate’ handles wildcards in the pattern slightly differently than ‘find’ (*note Shell Pattern Matching::). The file name databases contain lists of files that were on the system when the databases were last updated. The system administrator can choose the file name of the default database, the frequency with which the databases are updated, and the directories for which they contain entries. Here is how to select which file name databases ‘locate’ searches. The default is system-dependent. At the time this document was generated, the default was ‘/usr/local/var/locatedb’.

‘—database=PATH’ ‘-d PATH’ Instead of searching the default file name database, search the file name databases in PATH, which is a colon-separated list of database file names. You can also use the environment variable ‘LOCATE_PATH’ to set the list of database files to search. The option overrides the environment variable if both are used. GNU ‘locate’ can read file name databases generated by the ‘slocate’ package. However, these generally contain a list of all the files on the system, and so when using this database, ‘locate’ will produce output only for files which are accessible to you. *Note Invoking locate::, for a description of the ‘—existing’ option which is used to do this. The ‘updatedb’ program can also generate database in a format compatible with ‘slocate’. *Note Invoking updatedb::, for a description of its ‘—dbformat’ and ‘—output’ options.

2.3.4 Shell Pattern Matching

'find' and 'locate' can compare file names, or parts of file names, to

shell patterns. A “shell pattern” is a string that may contain the following special characters, which are known as “wildcards” or “metacharacters”.

You must quote patterns that contain metacharacters to prevent the shell from expanding them itself.

Double and single quotes both work; so does escaping with a backslash.

'*'

Matches any zero or more characters.

'?'

Matches any one character.

'[STRING]'

Matches exactly one character that is a member of the string STRING. This is called a “character class”. As a shorthand, STRING may contain ranges, which consist of two characters with a dash between them. For example, the class ‘[a-z0-9_]’ matches a lowercase letter, a number, or an underscore. You can negate a class by placing a ’!’ or ’^’ immediately after the opening bracket. Thus, ’[^A-Z@]’ matches any character except an uppercase letter or an at sign.

''

Removes the special meaning of the character that follows it. This works even in character classes.

In the find tests that do shell pattern matching (-name, -wholename, etc.), wildcards in the pattern will match a . at the beginning of a file name.

This is also the case for locate.

Thus, find -name '*macs' will match a file named .emacs, as will locate '*macs'.

Slash characters have no special significance in the shell pattern matching that ‘find’ and ‘locate’ do, unlike in the shell, in which wildcards do not match them. Therefore, a pattern ‘foobar’ can match a file name ‘foo3/bar’, and a pattern ‘./srsc’ can match a file name ‘./src/misc’. If you want to locate some files with the ‘locate’ command but don’t need to see the full list you can use the ‘—limit’ option to see just a small number of results, or the ‘—count’ option to display only the total number of matches.

There are two ways that files can be linked together. “Symbolic links” are a special type of file whose contents are a portion of the name of another file. “Hard links” are multiple directory entries for one file; the file names all have the same index node (“inode”) number on the disk.

Symbolic links are names that reference other files. GNU ‘find’ will handle symbolic links in one of two ways; firstly, it can dereference the links for you - this means that if it comes across a symbolic link, it examines the file that the link points to, in order to see if it matches the criteria you have specified. Secondly, it can check the link itself in case you might be looking for the actual link. If the file that the symbolic link points to is also within the directory hierarchy you are searching with the ‘find’ command, you may not see a great deal of difference between these two alternatives. By default, ‘find’ examines symbolic links themselves when it finds them (and, if it later comes across the linked-to file, it will examine that, too). If you would prefer ‘find’ to dereference the links and examine the file that each link points to, specify the ‘-L’ option to ‘find’. You can explicitly specify the default behaviour by using the ‘-P’ option. The ‘-H’ option is a half-way-between option which ensures that any symbolic links listed on the command line are dereferenced, but other symbolic links are not. Symbolic links are different from “hard links” in the sense that you need permission to search the directories in the linked-to file name to dereference the link. This can mean that even if you specify the ‘-L’ option, ‘find’ may not be able to determine the properties of the file that the link points to (because you don’t have sufficient permission). In this situation, ‘find’ uses the properties of the link itself. This also occurs if a symbolic link exists but points to a file that is missing. The options controlling the behaviour of ‘find’ with respect to links are as follows:

‘-P’ ‘find’ does not dereference symbolic links at all. This is the default behaviour. This option must be specified before any of the file names on the command line. ‘-H’ ‘find’ does not dereference symbolic links (except in the case of file names on the command line, which are dereferenced). If a symbolic link cannot be dereferenced, the information for the symbolic link itself is used. This option must be specified before any of the file names on the command line. ‘-L’ ‘find’ dereferences symbolic links where possible, and where this is not possible it uses the properties of the symbolic link itself. This option must be specified before any of the file names on the command line. Use of this option also implies the same behaviour as the ‘-noleaf’ option. If you later use the ‘-H’ or ‘-P’ options, this does not turn off ‘-noleaf’. Actions that can cause symbolic links to become broken while ‘find’ is executing (for example ‘-delete’) can give rise to confusing behaviour. Take for example the command line ‘find -L . -type d -delete’. This will delete empty directories. If a subtree includes only directories and symbolic links to directoires, this command may still not successfully delete it, since deletion of the target of the symbolic link will cause the symbolic link to become broken and ‘-type d’ is false for broken symbolic links.

‘-follow’ This option forms part of the “expression” and must be specified after the file names, but it is otherwise equivalent to ‘-L’. The ‘-follow’ option affects only those tests which appear after it on the command line. This option is deprecated. Where possible, you should use ‘-L’ instead. The following differences in behaviour occur when the ‘-L’ option is used:

  • ‘find’ follows symbolic links to directories when searching directory trees.
  • ‘-lname’ and ‘-ilname’ always return false (unless they happen to match broken symbolic links).
  • ‘-type’ reports the types of the files that symbolic links point to. This means that in combination with ‘-L’, ‘-type l’ will be true only for broken symbolic links. To check for symbolic links when ‘-L’ has been specified, use ‘-xtype l’.
  • Implies ‘-noleaf’ (*note Directories::). If the ‘-L’ option or the ‘-H’ option is used, the file names used as arguments to ‘-newer’, ‘-anewer’, and ‘-cnewer’ are dereferenced and the timestamp from the pointed-to file is used instead (if possible - otherwise the timestamp from the symbolic link is used).

— Test: -lname pattern — Test: -ilname pattern True if the file is a symbolic link whose contents match shell pattern PATTERN. For ‘-ilname’, the match is case-insensitive. *Note Shell Pattern Matching::, for details about the PATTERN argument. If the ‘-L’ option is in effect, this test will always return false for symbolic links unless they are broken. So, to list any symbolic links to ‘sysdep.c’ in the current directory and its subdirectories, you can do: find . -lname ‘*sysdep.c’

Hard links allow more than one name to refer to the same file on a file system, i.e., to the same inode. To find all the names which refer to the same file as NAME, use ‘-samefile NAME’.

— Test: -samefile NAME True if the file is a hard link to the same inode as NAME. This implies that NAME and the file reside on the same file system, i.e., they have the same device number. Unless the ‘-L’ option is also given to follow symbolic links, one may confine the search to one file system by using the ‘-xdev’ option. This is useful because hard links cannot point outside a single file system, so this can cut down on needless searching. If the ‘-L’ option is in effect, then dereferencing of symbolic links applies both to the NAME argument of the ‘-samefile’ primary and to each file examined during the traversal of the directory hierarchy. Therefore, ‘find -L -samefile NAME’ will find both hard links and symbolic links pointing to the file referenced by NAME. ‘find’ also allows searching for files by inode number. This can occasionally be useful in diagnosing problems with file systems; for example, ‘fsck’ and ‘lsof’ tend to print inode numbers. Inode numbers also occasionally turn up in log messages for some types of software. You can learn a file’s inode number and the number of links to it by running ‘ls -li’, ‘stat’ or ‘find -ls’. You can search for hard links to inode number NUM by using ‘-inum NUM’. If there are any file system mount points below the directory where you are starting the search, use the ‘-xdev’ option unless you are also using the ‘-L’ option. Using ‘-xdev’ saves needless searching, since hard links to a file must be on the same file system. *Note Filesystems::.

— Test: -inum n True if the file has inode number N. The ’+’ and ’-’ qualifiers also work, though these are rarely useful. Please note that the ‘-inum’ primary simply compares the inode number against the given N. This means that a search for a certain inode number in several file systems may return several files with that inode number, but as each file system has its own device number, those files are not necessarily hard links to the same file. Therefore, it is much of the time easier to use ‘-samefile’ rather than this option. ‘find’ also allows searching for files that have a certain number of links, with ‘-links’. A directory normally has at least two hard links: the entry named in its parent directory, and the ’.’ entry inside of the directory. If a directory has subdirectories, each of those also has a hard link called ’..’ to its parent directory. The ’.’ and ’..’ directory entries are not normally searched unless they are mentioned on the ‘find’ command line.

— Test: -links n File has N hard links.

— Test: -links +n File has more than N hard links.

— Test: -links -n File has fewer than N hard links.

2.5 Time

Each file has three timestamps, which record the last time that certain operations were performed on the file:

  1. access (read the file’s contents)
  2. change the status (modify the file or its attributes)
  3. modify (change the file’s contents) Some systems also provide a timestamp that indicates when a file was created. For example, the UFS2 filesystem under NetBSD-3.1 records the birth time of each file. This information is also available under other versions of BSD and some versions of Cygwin. However, even on systems which support file birth time, files may exist for which this information was not recorded (for example, UFS1 file systems simply do not contain this information). You can search for files whose timestamps are within a certain age range, or compare them to other timestamps.

2.5.1 Age Ranges

These tests are mainly useful with ranges (‘+N’ and ‘-N’).

— Test: -atime n — Test: -ctime n — Test: -mtime n True if the file was last accessed (or its status changed, or it was modified) N*24 hours ago. The number of 24-hour periods since the file’s timestamp is always rounded down; therefore 0 means “less than 24 hours ago”, 1 means “between 24 and 48 hours ago”, and so forth. Fractional values are supported but this only really makes sense for the case where ranges (‘+N’ and ‘-N’) are used.

— Test: -amin n — Test: -cmin n — Test: -mmin n True if the file was last accessed (or its status changed, or it was modified) N minutes ago. These tests provide finer granularity of measurement than ‘-atime’ et al., but rounding is done in a similar way (again, fractions are supported). For example, to list files in ‘/u/bill’ that were last read from 2 to 6 minutes ago: find /u/bill -amin +2 -amin -6

-daystart

Measure times from the beginning of today rather than from 24 hours ago. So, to list the regular files in your home directory that were modified yesterday, do find ~/ -daystart -type f -mtime 1 The ‘-daystart’ option is unlike most other options in that it has an effect on the way that other tests are performed. The affected tests are ‘-amin’, ‘-cmin’, ‘-mmin’, ‘-atime’, ‘-ctime’ and ‘-mtime’. The ‘-daystart’ option only affects the behaviour of any tests which appear after it on the command line.

2.5.2 Comparing Timestamps

— Test: -newerXY reference Succeeds if timestamp ‘X’ of the file being considered is newer than timestamp ‘Y’ of the file ‘reference’. The letters ‘X’ and ‘Y’ can be any of the following letters: ‘a’ Last-access time of ‘reference’ ‘B’ Birth time of ‘reference’ (when this is not known, the test cannot succeed) ‘c’ Last-change time of ‘reference’ ‘m’ Last-modification time of ‘reference’ ‘t’ The ‘reference’ argument is interpreted as a literal time, rather than the name of a file. *Note Date input formats::, for a description of how the timestamp is understood. Tests of the form ‘-newerXt’ are valid but tests of the form ‘-newertY’ are not. For example the test ‘-newerac /tmp/foo’ succeeds for all files which have been accessed more recently than ‘/tmp/foo’ was changed. Here ‘X’ is ‘a’ and ‘Y’ is ‘c’. Not all files have a known birth time. If ‘Y’ is ‘b’ and the birth time of ‘reference’ is not available, ‘find’ exits with an explanatory error message. If ‘X’ is ‘b’ and we do not know the birth time the file currently being considered, the test simply fails (that is, it behaves like ‘-false’ does). Some operating systems (for example, most implementations of Unix) do not support file birth times. Some others, for example NetBSD-3.1, do. Even on operating systems which support file birth times, the information may not be available for specific files. For example, under NetBSD, file birth times are supported on UFS2 file systems, but not UFS1 file systems. There are two ways to list files in ‘/usr’ modified after February 1 of the current year. One uses ‘-newermt’: find /usr -newermt “Feb 1” The other way of doing this works on the versions of find before 4.3.3: touch -t 02010000 /tmp/stamp rm -f /tmp/stamp$$

— Test: -anewer reference — Test: -cnewer reference — Test: -newer reference True if the time of the last access (or status change or data modification) of the current file is more recent than that of the last data modification of the REFERENCE file. As such, ‘-anewer’ is equivalent to ‘-neweram’, ‘-cnewer’ to ‘-newercm’, and ‘-newer’ to ‘-newermm’. If REFERENCE is a symbolic link and the ‘-H’ option or the ‘-L’ option is in effect, then the time of the last data modification of the file it points to is always used. These tests are affected by ‘-follow’ only if ‘-follow’ comes before them on the command line. *Note Symbolic Links::, for more information on ‘-follow’. As an example, to list any files modified since ‘/bin/sh’ was last modified: find . -newer /bin/sh

— Test: -used n True if the file was last accessed N days after its status was last changed. Useful for finding files that are not being used, and could perhaps be archived or removed to save disk space.

2.6 Size

— Test: -size n[bckwMG] True if the file uses N units of space, rounding up. The units are 512-byte blocks by default, but they can be changed by adding a one-character suffix to N: ‘b’ 512-byte blocks (never 1024) ‘c’ bytes ‘w’ 2-byte words ‘k’ Kibibytes (KiB, units of 1024 bytes) ‘M’ Mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) ‘G’ Gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The ‘b’ suffix always considers blocks to be 512 bytes. This is not affected by the setting (or non-setting) of the ‘POSIXLY_CORRECT’ environment variable. This behaviour is different from the behaviour of the ‘-ls’ action). If you want to use 1024-byte units, use the ‘k’ suffix instead. The number can be prefixed with a ’+’ or a ’-‘. A plus sign indicates that the test should succeed if the file uses at least N units of storage (a common use of this test) and a minus sign indicates that the test should succeed if the file uses less than N units of storage; i.e., an exact size of N units does not match. Bear in mind that the size is rounded up to the next unit. Therefore ‘-size -1M’ is not equivalent to ‘-size -1048576c’. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. There is no ’=’ prefix, because that’s the default anyway. The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it’s consistent with the result you get for ‘ls -l’. This handling of sparse files differs from the output of the ‘%k’ and ‘%b’ format specifiers for the ‘-printf’ predicate.

— Test: -empty True if the file is empty and is either a regular file or a directory. This might help determine good candidates for deletion. This test is useful with ‘-depth’ (*note Directories::) and ‘-delete’ (*note Single File::).

2.7 Type

— Test: -type c True if the file is of type C: ‘b’ block (buffered) special ‘c’ character (unbuffered) special ‘d’ directory ‘p’ named pipe (FIFO) ‘f’ regular file ‘l’ symbolic link; if ‘-L’ is in effect, this is true only for broken symbolic links. If you want to search for symbolic links when ‘-L’ is in effect, use ‘-xtype’ instead of ‘-type’. ’s’ socket ‘D’ door (Solaris) As a GNU extension, multiple file types can be provided as a combined list separated by comma ’,‘. For example, ‘-type f,d,l’ is logically interpreted as ’( -type f -o -type d -o -type l )‘.

— Test: -xtype c This test behaves the same as ‘-type’ unless the file is a symbolic link. If the file is a symbolic link, the result is as follows (in the table below, ‘X’ should be understood to represent any letter except ‘l’): ”-P -xtype l” True if the symbolic link is broken ”-P -xtype X” True if the (ultimate) target file is of type ‘X’. ”-L -xtype l” Always true ”-L -xtype X” False unless the symbolic link is broken In other words, for symbolic links, ‘-xtype’ checks the type of the file that ‘-type’ does not check. The ‘-H’ option also affects the behaviour of ‘-xtype’. When ‘-H’ is in effect, ‘-xtype’ behaves as if ‘-L’ had been specified when examining files listed on the command line, and as if ‘-P’ had been specified otherwise. If neither ‘-H’ nor ‘-L’ was specified, ‘-xtype’ behaves as if ‘-P’ had been specified. *Note Symbolic Links::, for more information on ‘-follow’ and ‘-L’.

2.8 Owner

— Test: -user uname — Test: -group gname True if the file is owned by user UNAME (belongs to group GNAME). A numeric ID is allowed.

— Test: -uid n — Test: -gid n True if the file’s numeric user ID (group ID) is N. These tests support ranges (‘+N’ and ‘-N’), unlike ‘-user’ and ‘-group’.

— Test: -nouser — Test: -nogroup True if no user corresponds to the file’s numeric user ID (no group corresponds to the numeric group ID). These cases usually mean that the files belonged to users who have since been removed from the system. You probably should change the ownership of such files to an existing user or group, using the ‘chown’ or ‘chgrp’ program.

2.9 File Mode Bits

*Note File Permissions::, for information on how file mode bits are structured and how to specify them. Four tests determine what users can do with files. These are ‘-readable’, ‘-writable’, ‘-executable’ and ‘-perm’. The first three tests ask the operating system if the current user can perform the relevant operation on a file, while ‘-perm’ just examines the file’s mode. The file mode may give a misleading impression of what the user can actually do, because the file may have an access control list, or exist on a read-only filesystem, for example. Of these four tests though, only ‘-perm’ is specified by the POSIX standard. The ‘-readable’, ‘-writable’ and ‘-executable’ tests are implemented via the ‘access’ system call. This is implemented within the operating system itself. If the file being considered is on an NFS filesystem, the remote system may allow or forbid read or write operations for reasons of which the NFS client cannot take account. This includes user-ID mapping, either in the general sense or the more restricted sense in which remote superusers are treated by the NFS server as if they are the local user ‘nobody’ on the NFS server. None of the tests in this section should be used to verify that a user is authorised to perform any operation (on the file being tested or any other file) because of the possibility of a race condition. That is, the situation may change between the test and an action being taken on the basis of the result of that test.

— Test: -readable True if the file can be read by the invoking user.

— Test: -writable True if the file can be written by the invoking user. This is an in-principle check, and other things may prevent a successful write operation; for example, the filesystem might be full.

— Test: -executable True if the file can be executed/searched by the invoking user.

— Test: -perm pmode True if the file’s mode bits match PMODE, which can be either a symbolic or numeric MODE (*note File Permissions::) optionally prefixed by ’-’ or ’/‘. Note that PMODE starts with all file mode bits cleared, i.e., does not relate to the process’s file creation bit mask (also known as ‘umask’). A PMODE that starts with neither ’-’ nor ’/’ matches if MODE exactly matches the file mode bits. (To avoid confusion with an obsolete GNU extension, MODE must not start with a ’+’ immediately followed by an octal digit.) A PMODE that starts with ’-’ matches if all the file mode bits set in MODE are set for the file; bits not set in MODE are ignored. A PMODE that starts with ’/’ matches if any of the file mode bits set in MODE are set for the file; bits not set in MODE are ignored. This is a GNU extension. If you don’t use the ’/’ or ’-’ form with a symbolic mode string, you may have to specify a rather complex mode string. For example ‘-perm g=w’ will only match files that have mode 0020 (that is, ones for which group write permission is the only file mode bit set). It is more likely that you will want to use the ’/’ or ’-’ forms, for example ‘-perm -g=w’, which matches any file with group write permission. ‘-perm 664’ Match files that have read and write permission for their owner, and group, but that the rest of the world can read but not write to. Do not match files that meet these criteria but have other file mode bits set (for example if someone can execute/search the file). ‘-perm -664’ Match files that have read and write permission for their owner, and group, but that the rest of the world can read but not write to, without regard to the presence of any extra file mode bits (for example the executable bit). This matches a file with mode 0777, for example. ‘-perm /222’ Match files that are writable by somebody (their owner, or their group, or anybody else). ‘-perm /022’ Match files that are writable by their group or everyone else - the latter often called “other”. The files don’t have to be writable by both the group and other to be matched; either will do. ‘-perm /g+w,o+w’ As above. ‘-perm /g=w,o=w’ As above. ‘-perm -022’ Match files that are writable by both their group and everyone else. ‘-perm -g+w,o+w’ As above. ‘-perm -444 -perm /222 ! -perm /111’ Match files that are readable for everybody, have at least one write bit set (i.e., somebody can write to them), but that cannot be executed/searched by anybody. Note that in some shells the ’!’ must be escaped. ‘-perm -a+r -perm /a+w ! -perm /a+x’ As above. Warning: If you specify ‘-perm /000’ or ‘-perm /mode’ where the symbolic mode ‘mode’ has no bits set, the test matches all files. Versions of GNU ‘find’ prior to 4.3.3 matched no files in this situation.

— Test: -context pattern True if file’s SELinux context matches the pattern PATTERN. The pattern uses shell glob matching. This predicate is supported only on ‘find’ versions compiled with SELinux support and only when SELinux is enabled.

2.10 Contents

To search for files based on their contents, you can use the ‘grep’ program. For example, to find out which C source files in the current directory contain the string ‘thing’, you can do:

grep -l thing *.[ch]

If you also want to search for the string in files in subdirectories, you can combine ‘grep’ with ‘find’ and ‘xargs’, like this:

find . -name '*.[ch]' | xargs grep -l thing

The -l option causes grep to print only the names of files that contain the string, rather than the lines that contain it.

The string argument (‘thing’) is actually a regular expression, so it can contain metacharacters.

This method can be refined a little by using the -r option to make xargs not run grep if find produces no output, and using the find action -print0 and the xargs option -0 to avoid misinterpreting files whose names contain spaces:

find . -name '*.[ch]' -print0 | xargs -r -0 grep -l thing

For a fuller treatment of finding files whose contents match a pattern, see the manual page for ‘grep’.

2.11 Directories

Here is how to control which directories ‘find’ searches, and how it searches them. These two options allow you to process a horizontal slice of a directory tree.

-maxdepth levels

Descend at most LEVELS (a non-negative integer) levels of directories below the command line arguments. Using ‘-maxdepth 0’ means only apply the tests and actions to the command line arguments. find dir -maxdepth 1 dir dir/d1 find dir -mindepth 2 -maxdepth 4 dir/d1/d2 dir/d1/d2/d3 dir/d1/d2/d3/d4

По аналогии есть

Option:

-mindepth levels
-depth
-d

Action:

-prune

If the file is a directory, do not descend into it. The result is true. For example, to skip the directory ‘src/emacs’ and all files and directories under it, and print the names of the other files found:

find . -wholename './src/emacs' -prune -o -print

The above command will not print ./src/emacs among its list of results. This however is not due to the effect of the -prune action (which only prevents further descent, it doesn’t make sure we ignore that item). Instead, this effect is due to the use of -o.

Since the left hand side of the “or” condition has succeeded for ./src/emacs, it is not necessary to evaluate the right-hand-side (-print) at all for this particular file. If you wanted to print that directory name you could use either an extra -print action:

find . -wholename './src/emacs' -prune -print -o -print

or use the comma operator:

find . -wholename './src/emacs' -prune , -print

If the -depth option is in effect, the subdirectories will have already been visited in any case. Hence -prune has no effect in this case.

Because -delete implies -depth, using -prune in combination with -delete may well result in the deletion of more files than you intended.

— Action: -quit Exit immediately (with return value zero if no errors have occurred). This is different to ‘-prune’ because ‘-prune’ only applies to the contents of pruned directories, while ‘-quit’ simply makes ‘find’ stop immediately. No child processes will be left running. Any command lines which have been built by ‘-exec … +’ or ‘-execdir … +’ are invoked before the program is exited. After ‘-quit’ is executed, no more files specified on the command line will be processed. For example, ‘find /tmp/foo /tmp/bar -print -quit’ will print only ‘/tmp/foo’. One common use of ‘-quit’ is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit

Option:

-noleaf

Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its ’.’ entry. Additionally, its subdirectories (if any) each have a ’..’ entry linked to that directory. When ‘find’ is examining a directory, after it has statted 2 fewer subdirectories than the directory’s link count, it knows that the rest of the entries in the directory are non-directories (“leaf” files in the directory tree). If only the files’ names need to be examined, there is no need to stat them; this gives a significant increase in search speed.

Option:

-ignore_readdir_race

If a file disappears after its name has been read from a directory but before find gets around to examining the file with stat, don’t issue an error message.

If you don’t specify this option, an > error message will be issued.

Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true.

This option can be useful in system scripts (cron scripts, for example) that examine areas of the filesystem that change frequently (mail queues, temporary directories, and so forth), because this scenario is common for those sorts of directories.

Completely silencing error messages from find is undesirable, so this option neatly solves the problem. There is no way to search one part of the filesystem with this option on and part of it with this option off, though.

When this option is turned on and find discovers that one of the start-point files specified on the command line does not exist, no error message will be issued.

Option

-noignore_readdir_race

This option reverses the effect of the -ignore_readdir_race option.

2.12 Filesystems

A “filesystem” is a section of a disk, either on the local host or mounted from a remote host over a network. Searching network filesystems can be slow, so it is common to make ‘find’ avoid them. There are two ways to avoid searching certain filesystems. One way is to tell ‘find’ to only search one filesystem:

-xdev

-mount

Don’t descend directories on other filesystems. These options are synonyms. The other way is to check the type of filesystem each file is on, and not descend directories that are on undesirable filesystem types:

— Test: -fstype type True if the file is on a filesystem of type TYPE. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: autofs ext3 ext4 fuse.sshfs nfs proc sshfs sysfs ufs tmpfs xfs You can use ‘-printf’ with the ‘%F’ directive to see the types of your filesystems. The ‘%D’ directive shows the device number. *Note Print File Information::. ‘-fstype’ is usually used with ‘-prune’ to avoid searching remote filesystems (*note Directories::).

2.13 Combining Primaries With Operators

Operators build a complex expression from tests and actions. The operators are, in order of decreasing precedence:

’( EXPR )’ Force precedence. True if EXPR is true.

’! EXPR’ ‘-not EXPR’ True if EXPR is false. In some shells, it is necessary to protect the ’!’ from shell interpretation by quoting it.

‘EXPR1 EXPR2’ ‘EXPR1 -a EXPR2’ ‘EXPR1 -and EXPR2’ And; EXPR2 is not evaluated if EXPR1 is false.

‘EXPR1 -o EXPR2’ ‘EXPR1 -or EXPR2’ Or; EXPR2 is not evaluated if EXPR1 is true.

‘EXPR1 , EXPR2’ List; both EXPR1 and EXPR2 are always evaluated. True if EXPR2 is true. The value of EXPR1 is discarded. This operator lets you do multiple independent operations on one traversal, without depending on whether other operations succeeded. The two operations EXPR1 and EXPR2 are not always fully independent, since EXPR1 might have side effects like touching or deleting files, or it might use ‘-prune’ which would also affect EXPR2. ‘find’ searches the directory tree rooted at each file name by evaluating the expression from left to right, according to the rules of precedence, until the outcome is known (the left hand side is false for ‘-and’, true for ‘-or’), at which point ‘find’ moves on to the next file name. There are two other tests that can be useful in complex expressions:

— Test: -true Always true.

— Test: -false Always false.

3 Actions

There are several ways you can print information about the files that match the criteria you gave in the ‘find’ expression. You can print the information either to the standard output or to a file that you name. You can also execute commands that have the file names as arguments. You can use those commands as further filters to select files.

3.1 Print File Name

— Action: -print True; print the entire file name on the standard output, followed by a newline. If there is the faintest possibility that one of the files for which you are searching might contain a newline, you should use ‘-print0’ instead.

— Action: -fprint file True; print the entire file name into file FILE, followed by a newline. If FILE does not exist when ‘find’ is run, it is created; if it does exist, it is truncated to 0 bytes. The named output file is always created, even if no output is sent to it. The file names ‘/dev/stdout’ and ‘/dev/stderr’ are handled specially; they refer to the standard output and standard error output, respectively. If there is the faintest possibility that one of the files for which you are searching might contain a newline, you should use ‘-fprint0’ instead.

3.2 Print File Information

— Action: -ls True; list the current file in ‘ls -dils’ format on the standard output. The output looks like this: 204744 17 -rw-r—r— 1 djm staff 17337 Nov 2 1992 ./lwall-quotes The fields are: 1. The inode number of the file. *Note Hard Links::, for how to find files based on their inode number. 2. the number of blocks in the file. The block counts are of 1K blocks, unless the environment variable ‘POSIXLY_CORRECT’ is set, in which case 512-byte blocks are used. *Note Size::, for how to find files based on their size. 3. The file’s type and file mode bits. The type is shown as a dash for a regular file; for other file types, a letter like for ‘-type’ is used (*note Type::). The file mode bits are read, write, and execute/search for the file’s owner, its group, and other users, respectively; a dash means the permission is not granted. *Note File Permissions::, for more details about file permissions. *Note Mode Bits::, for how to find files based on their file mode bits. 4. The number of hard links to the file. 5. The user who owns the file. 6. The file’s group. 7. The file’s size in bytes. 8. The date the file was last modified. 9. The file’s name. ‘-ls’ quotes non-printable characters in the file names using C-like backslash escapes. This may change soon, as the treatment of unprintable characters is harmonised for ‘-ls’, ‘-fls’, ‘-print’, ‘-fprint’, ‘-printf’ and ‘-fprintf’.

— Action: -fls file True; like ‘-ls’ but write to FILE like ‘-fprint’ (*note Print File Name::). The named output file is always created, even if no output is sent to it.

— Action: -printf format True; print FORMAT on the standard output, interpreting ” escapes and ’%’ directives (more details in the following sections). Field widths and precisions can be specified as with the ‘printf’ C function. Format flags (like ’#’ for example) may not work as you expect because many of the fields, even numeric ones, are printed with %s. Numeric flags which are affected in this way include ‘G’, ‘U’, ‘b’, ‘D’, ‘k’ and ‘n’. This difference in behaviour means though that the format flag ’-’ will work; it forces left-alignment of the field. Unlike ‘-print’, ‘-printf’ does not add a newline at the end of the string. If you want a newline at the end of the string, add a ‘\n’. As an example, an approximate equivalent of ‘-ls’ with null-terminated filenames can be achieved with this ‘-printf’ format: find -printf “%i %4k %M %3n %-8u %-8g %8s %T+ %p\n->%l\0” | cat A practical reason for doing this would be to get literal filenames in the output, instead of ‘-ls”s backslash-escaped names. (Using ‘cat’ here prevents this happening for the ‘%p’ format specifier; *note Unusual Characters in File Names::). This format also outputs a uniform timestamp format. As for symbolic links, the format above outputs the target of the symbolic link on a second line, following ‘\n->‘. There is nothing following the arrow for file types other than symbolic links. Another approach, for complete consistency, would be to ‘-fprintf’ the symbolic links into a separate file, so they too can be null-terminated.

— Action: -fprintf file format True; like ‘-printf’ but write to FILE like ‘-fprint’ (*note Print File Name::). The output file is always created, even if no output is ever sent to it.

3.2.1 Escapes

The escapes that ‘-printf’ and ‘-fprintf’ recognise are:

‘\a’ Alarm bell. ‘\b’ Backspace. ‘\c’ Stop printing from this format immediately and flush the output. ‘\f’ Form feed. ‘\n’ Newline. ‘\r’ Carriage return. ‘\t’ Horizontal tab. ‘\v’ Vertical tab. ’\’ A literal backslash (”). ‘\0’ ASCII NUL. ‘\NNN’ The character whose ASCII code is NNN (octal). A ” character followed by any other character is treated as an ordinary character, so they both are printed, and a warning message is printed to the standard error output (because it was probably a typo).

3.2.2 Format Directives

‘-printf’ and ‘-fprintf’ support the following format directives to print information about the file being processed. The C ‘printf’ function, field width and precision specifiers are supported, as applied to string (%s) types. That is, you can specify “minimum field width”.“maximum field width” for each directive. Format flags (like ’#’ for example) may not work as you expect because many of the fields, even numeric ones, are printed with %s. The format flag ’-’ does work; it forces left-alignment of the field. ’%%’ is a literal percent sign. *Note Reserved and Unknown Directives::, for a description of how format directives not mentioned below are handled. A ’%’ at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading.

3.2.2.1 Name Directives

‘%p’ File’s name (not the absolute path name, but the name of the file as it was encountered by ‘find’ - that is, as a relative path from one of the starting points). ‘%f’ File’s name with any leading directories removed (only the last element). That is, the basename of the file. ‘%h’ Leading directories of file’s name (all but the last element and the slash before it). That is, the dirname of the file. If the file’s name contains no slashes (for example because it was named on the command line and is in the current working directory), then “%h” expands to ”.“. This prevents “%h/%f” expanding to “/foo”, which would be surprising and probably not desirable. ‘%P’ File’s name with the name of the command line argument under which it was found removed from the beginning. ‘%H’ Command line argument under which file was found. For some corner-cases, the interpretation of the ‘%f’ and ‘%h’ format directives is not obvious. Here is an example including some output: $ find
. .. / /tmp /tmp/TRACE compile compile/64/tests/find
-maxdepth 0 -printf ‘%p: [%h][%f]\n’ .: [.][.] ..: [.][..] /: [][/] /tmp: [][tmp] /tmp/TRACE: [/tmp][TRACE] compile: [.][compile] compile/64/tests/find: [compile/64/tests][find]

3.2.2.2 Ownership Directives

‘%g’ File’s group name, or numeric group ID if the group has no name. ‘%G’ File’s numeric group ID. ‘%u’ File’s user name, or numeric user ID if the user has no name. ‘%U’ File’s numeric user ID. ‘%m’ File’s mode bits (in octal). If you always want to have a leading zero on the number, use the ’#’ format flag, for example ’%#m’. The file mode bit numbers used are the traditional Unix numbers, which will be as expected on most systems, but if your system’s file mode bit layout differs from the traditional Unix semantics, you will see a difference between the mode as printed by ‘%m’ and the mode as it appears in ‘struct stat’.

‘%M’ File’s type and mode bits (in symbolic form, as for ‘ls’). This directive is supported in findutils 4.2.5 and later.

3.2.2.3 Size Directives

‘%k’ The amount of disk space used for this file in 1K blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file (that is, it has “holes”). ‘%b’ The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file (that is, it has “holes”). ‘%s’ File’s size in bytes. ‘%S’ File’s sparseness. This is calculated as ‘(BLOCKSIZE*st_blocks / st_size)‘. The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks and have few holes may have a value which is greater than 1.0. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file’s sparseness is assumed to be 1.0.

3.2.2.4 Location Directives

‘%d’ File’s depth in the directory tree (depth below a file named on the command line, not depth below the root directory). Files named on the command line have a depth of 0. Subdirectories immediately below them have a depth of 1, and so on. ‘%D’ The device number on which the file exists (the ‘st_dev’ field of ‘struct stat’), in decimal. ‘%F’ Type of the filesystem the file is on; this value can be used for ‘-fstype’ (*note Directories::). ‘%l’ Object of symbolic link (empty string if file is not a symbolic link). ‘%i’ File’s inode number (in decimal). ‘%n’ Number of hard links to file. ‘%y’ Type of the file as used with ‘-type’. If the file is a symbolic link, ‘l’ will be printed. ‘%Y’ Type of the file as used with ‘-type’. If the file is a symbolic link, it is dereferenced. If the file is a broken symbolic link, ‘N’ is printed. When determining the type of the target of a symbolic link, and a loop is encountered, then ‘L’ is printed (e.g. for a symbolic link to itself); ’?’ is printed for any other error (like e.g. ‘permission denied’).

3.2.2.5 Time Directives

Some of these directives use the C ‘ctime’ function. Its output depends on the current locale, but it typically looks like Wed Nov 2 00:42:36 1994

‘%a’ File’s last access time in the format returned by the C ‘ctime’ function.

‘%AK’ File’s last access time in the format specified by K (*note Time Formats::).

‘%BK’ File’s birth time, i.e., its creation time, in the format specified by K (*note Time Formats::). This directive produces an empty string if the underlying operating system or filesystem does not support birth times.

‘%c’ File’s last status change time in the format returned by the C ‘ctime’ function.

‘%CK’ File’s last status change time in the format specified by K (*note Time Formats::).

‘%t’ File’s last modification time in the format returned by the C ‘ctime’ function.

‘%TK’ File’s last modification time in the format specified by K (*note Time Formats::).

3.2.2.6 Other Directives

‘%Z’ File’s SELinux context, or empty string if the file has no SELinux context.

3.2.2.7 Reserved and Unknown Directives

The ’%(’, ’%{’ and ’%[’ format directives, with or without field with and precision specifications, are reserved for future use. Don’t use them and don’t rely on current experiment to predict future behaviour. To print ’(’, simply use ’(’ rather than ’%(‘. Likewise for ’{’ and ’[‘. Similarly, a ’%’ character followed by any other unrecognised character (i.e., not a known directive or ‘printf’ field width and precision specifier), is discarded (but the unrecognised character is printed), and a warning message is printed to the standard error output (because it was probably a typo). Don’t rely on this behaviour, because other directives may be added in the future.

3.2.3 Time Formats

Below is an incomplete list of formats for the directives ‘%A’, ‘%B’, ‘%C’, and ‘%T’, which print the file’s timestamps. Please refer to the documentation of ‘strftime’ for the full list. Some of these formats might not be available on all systems, due to differences in the implementation of the C ‘strftime’ function.

3.2.3.1 Time Components

The following format directives print single components of the time.

‘H’ hour (00..23) ‘I’ hour (01..12) ‘k’ hour ( 0..23) ‘l’ hour ( 1..12) ‘p’ locale’s AM or PM ‘Z’ time zone (e.g., EDT), or nothing if no time zone is determinable ‘M’ minute (00..59) ‘S’ second (00..61). There is a fractional part. ’@’ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. The fractional part of the seconds field is of indeterminate length and precision. That is, the length of the fractional part of the seconds field will in general vary between findutils releases and between systems. This means that it is unwise to assume that field has any specific length. The length of this field is not usually a guide to the precision of timestamps in the underlying file system.

3.2.3.2 Date Components

The following format directives print single components of the date.

‘a’ locale’s abbreviated weekday name (Sun..Sat) ‘A’ locale’s full weekday name, variable length (Sunday..Saturday) ‘b’ ‘h’ locale’s abbreviated month name (Jan..Dec) ‘B’ locale’s full month name, variable length (January..December) ‘m’ month (01..12) ‘d’ day of month (01..31) ‘w’ day of week (0..6) ‘j’ day of year (001..366) ‘U’ week number of year with Sunday as first day of week (00..53) ‘W’ week number of year with Monday as first day of week (00..53) ‘Y’ year (1970…) ‘y’ last two digits of year (00..99)

3.2.3.3 Combined Time Formats

The following format directives print combinations of time and date components.

‘r’ time, 12-hour (hh:mm:ss [AP]M) ‘T’ time, 24-hour (hh:mm:ss.xxxxxxxxxx) ‘X’ locale’s time representation (H:M:S). The seconds field includes a fractional part. ‘c’ locale’s date and time in ctime format (Sat Nov 04 12:02:33 EST 1989). This format does not include any fractional part in the seconds field. ‘D’ date (mm/dd/yy) ‘F’ date (yyyy-mm-dd) ‘x’ locale’s date representation (mm/dd/yy) ’+’ Date and time, separated by ’+’, for example ‘2004-04-28+22:22:05.0000000000’. The time is given in the current timezone (which may be affected by setting the ‘TZ’ environment variable). This is a GNU extension. The seconds field includes a fractional part.

3.2.4 Formatting Flags

The ‘%m’ and ‘%d’ directives support the ’#’, ‘0’ and ’+’ flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include ‘G’, ‘U’, ‘b’, ‘D’, ‘k’ and ‘n’. All fields support the format flag ’-’, which makes fields left-aligned. That is, if the field width is greater than the actual contents of the field, the requisite number of spaces are printed after the field content instead of before it.

3.3 Run Commands

You can use the list of file names created by ‘find’ or ‘locate’ as arguments to other commands. In this way you can perform arbitrary actions on the files.

3.3.1 Single File

Here is how to run a command on one file at a time.

— Action: -execdir command ; Execute COMMAND; true if COMMAND returns zero. ‘find’ takes all arguments after ‘-execdir’ to be part of the command until an argument consisting of ’;’ is reached. It replaces the string ’{}’ by the current file name being processed everywhere it occurs in the command. Both of these constructions need to be escaped (with a ”) or quoted to protect them from expansion by the shell. The command is executed in the directory which ‘find’ was searching at the time the action was executed (that is, {} will expand to a file in the local directory). For example, to compare each C header file in or below the current directory with the file ‘/tmp/master’: find . -name ‘*.h’ -execdir diff -u ’{}’ /tmp/master ’;’ If you use ‘-execdir’, you must ensure that the ‘PATH’ variable contains only absolute directory names. Having an empty element in ‘PATH’ or explicitly including ’.’ (or any other non-absolute name) is insecure. GNU find will refuse to run if you use ‘-execdir’ and it thinks your ‘PATH’ setting is insecure. For example:

‘/bin:/usr/bin:’ Insecure; empty path element (at the end) ’:/bin:/usr/bin:/usr/local/bin’ Insecure; empty path element (at the start) ‘/bin:/usr/bin::/usr/local/bin’ Insecure; empty path element (two colons in a row) ‘/bin:/usr/bin:.:/usr/local/bin’ Insecure; ’.’ is a path element (’.’ is not an absolute file name) ‘/bin:/usr/bin:sbin:/usr/local/bin’ Insecure; ‘sbin’ is not an absolute file name ‘/bin:/usr/bin:/sbin:/usr/local/bin’ Secure (if you control the contents of those directories and any access to them) Another similar option, ‘-exec’ is supported, but is less secure. *Note Security Considerations::, for a discussion of the security problems surrounding ‘-exec’.

— Action: -exec command ; This insecure variant of the ‘-execdir’ action is specified by POSIX. Like ‘-execdir command ;’ it is true if zero is returned by COMMAND. The main difference is that the command is executed in the directory from which ‘find’ was invoked, meaning that ’{}’ is expanded to a relative path starting with the name of one of the starting directories, rather than just the basename of the matched file. While some implementations of ‘find’ replace the ’{}’ only where it appears on its own in an argument, GNU ‘find’ replaces ’{}’ wherever it appears.

3.3.2 Multiple Files

Sometimes you need to process files one at a time. But usually this is not necessary, and, it is faster to run a command on as many files as possible at a time, rather than once per file. Doing this saves on the time it takes to start up the command each time. The ‘-execdir’ and ‘-exec’ actions have variants that build command lines containing as many matched files as possible.

— Action: -execdir command {} + This works as for ‘-execdir command ;’, except that the result is always true, and the ’{}’ at the end of the command is expanded to a list of names of matching files. This expansion is done in such a way as to avoid exceeding the maximum command line length available on the system. Only one ’{}’ is allowed within the command, and it must appear at the end, immediately before the ’+‘. A ’+’ appearing in any position other than immediately after ’{}’ is not considered to be special (that is, it does not terminate the command).

— Action: -exec command {} + This insecure variant of the ‘-execdir’ action is specified by POSIX. The main difference is that the command is executed in the directory from which ‘find’ was invoked, meaning that ’{}’ is expanded to a relative path starting with the name of one of the starting directories, rather than just the basename of the matched file. The result is always true. Before ‘find’ exits, any partially-built command lines are executed. This happens even if the exit was caused by the ‘-quit’ action. However, some types of error (for example not being able to invoke ‘stat()’ on the current directory) can cause an immediate fatal exit. In this situation, any partially-built command lines will not be invoked (this prevents possible infinite loops). At first sight, it looks like the list of filenames to be processed can only be at the end of the command line, and that this might be a problem for some commands (‘cp’ and ‘rsync’ for example). However, there is a slightly obscure but powerful workaround for this problem which takes advantage of the behaviour of ‘sh -c’: find startpoint -tests … -exec sh -c ‘scp ”@” remote:/dest’ and the shell expands ‘”HOME -name ’.c’ -print` However, that method produces an error if the length of the ‘.c’ file names exceeds the operating system’s command line length limit. ‘xargs’ avoids that problem by running the command as many times as necessary without exceeding the limit: find $HOME -name ’.c’ -print | xargs grep -l sprintf However, if the command needs to have its standard input be a terminal (‘less’, for example), you have to use the shell command substitution method or use either the ‘—arg-file’ option or the ‘—open-tty’ option of ‘xargs’. The ‘xargs’ command will usually process all of its input, building command lines and executing them. The processing stops earlier and immediately if the tool reads a line containing the end-of-file marker string specified with the ‘—eof’ option, or if one of the launched commands exits with a status of 255. The latter will cause ‘xargs’ to issue an error message and exit with status 124.

3.3.2.1 Unsafe File Name Handling

Because file names can contain quotes, backslashes, blank characters, and even newlines, it is not safe to process them using ‘xargs’ in its default mode of operation. But since most files’ names do not contain blanks, this problem occurs only infrequently. If you are only searching through files that you know have safe names, then you need not be concerned about it. Error messages issued by ‘find’ and ‘locate’ quote unusual characters in file names in order to prevent unwanted changes in the terminal’s state. In many applications, if ‘xargs’ botches processing a file because its name contains special characters, some data might be lost. The importance of this problem depends on the importance of the data and whether anyone notices the loss soon enough to correct it. However, here is an extreme example of the problems that using blank-delimited names can cause. If the following command is run daily from ‘cron’, then any user can remove any file on the system: find / -name ’#*’ -atime +7 -print | xargs rm For example, you could do something like this: eg$ echo > ’# vmunix’

and then ‘cron’ would delete ‘/vmunix’, if it ran ‘xargs’ with ’/’ as its current directory. To delete other files, for example ‘/u/joeuser/.plan’, you could do this: eg mkdir '# ' eg cd ’# ’ eg mkdir u u/joeuser u/joeuser/.plan' ' eg echo > u/joeuser/.plan’ /#foo’ eg find . -name ’#*’ -print | xargs echo ./# ./# /u/joeuser/.plan /#foo

3.3.2.2 Safe File Name Handling

Here is how to make ‘find’ output file names so that they can be used by other programs without being mangled or misinterpreted. You can process file names generated this way by giving the ‘-0’ or ‘—null’ option to GNU ‘xargs’, GNU ‘tar’, GNU ‘cpio’, or ‘perl’.

— Action: -print0 True; print the entire file name on the standard output, followed by a null character.

— Action: -fprint0 file True; like ‘-print0’ but write to FILE like ‘-fprint’ (*note Print File Name::). The output file is always created. As of findutils version 4.2.4, the ‘locate’ program also has a ‘—null’ option which does the same thing. For similarity with ‘xargs’, the short form of the option ‘-0’ can also be used. If you want to be able to handle file names safely but need to run commands which want to be connected to a terminal on their input, you can use the ‘—open-tty’ option to ‘xargs’ or the ‘—arg-file’ option to ‘xargs’ like this: find / -name xyzzy -print0 > list xargs —null —arg-file=list munge The example above runs the ‘munge’ program on all the files named ‘xyzzy’ that we can find, but ‘munge”s input will still be the terminal (or whatever the shell was using as standard input). If your shell has the “process substitution” feature ’<(…)’, you can do this in just one step: xargs —null —arg-file=<(find / -name xyzzy -print0) munge

3.3.2.3 Unusual Characters in File Names

As discussed above, you often need to be careful about how the names of files are handled by ‘find’ and other programs. If the output of ‘find’ is not going to another program but instead is being shown on a terminal, this can still be a problem. For example, some character sequences can reprogram the function keys on some terminals. *Note Security Considerations::, for a discussion of other security problems relating to ‘find’. Unusual characters are handled differently by various actions, as described below.

‘-print0’ ‘-fprint0’ Always print the exact file name, unchanged, even if the output is going to a terminal. ‘-ok’ ‘-okdir’ Always print the exact file name, unchanged. This will probably change in a future release. ‘-ls’ ‘-fls’ Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example ‘\f’, ’”’). Other unusual characters are printed using an octal escape. Other printable characters (for ‘-ls’ and ‘-fls’ these are the characters between octal 041 and 0176) are printed as-is. ‘-printf’ ‘-fprintf’ If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use: %D, %F, %H, %Y, %y These expand to values which are not under control of files’ owners, and so are printed as-is. %a, %b, %c, %d, %g, %G, %i, %k, %m, %M, %n, %s, %t, %u, %U These have values which are under the control of files’ owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. %f, %h, %l, %p, %P The output of these directives is quoted if the output is going to a terminal. The setting of the ‘LC_CTYPE’ environment variable is used to determine which characters need to be quoted. This quoting is performed in the same way as for GNU ‘ls’. This is not the same quoting mechanism as the one used for ‘-ls’ and ‘fls’. If you are able to decide what format to use for the output of ‘find’ then it is normally better to use ‘\0’ as a terminator than to use newline, as file names can contain white space and newline characters. ‘-print’ ‘-fprint’ Quoting is handled in the same way as for the ‘%p’ directive of ‘-printf’ and ‘-fprintf’. If you are using ‘find’ in a script or in a situation where the matched files might have arbitrary names, you should consider using ‘-print0’ instead of ‘-print’. The ‘locate’ program quotes and escapes unusual characters in file names in the same way as ‘find”s ‘-print’ action. The behaviours described above may change soon, as the treatment of unprintable characters is harmonised for ‘-ls’, ‘-fls’, ‘-print’, ‘-fprint’, ‘-printf’ and ‘-fprintf’.

3.3.2.4 Limiting Command Size

‘xargs’ gives you control over how many arguments it passes to the command each time it executes it. By default, it uses up to ‘ARG_MAX’ - 2k, or 128k, whichever is smaller, characters per command. It uses as many lines and arguments as fit within that limit. The following options modify those values.

‘—no-run-if-empty’ ‘-r’ If the standard input does not contain any nonblanks, do not run the command. By default, the command is run once even if there is no input. This option is a GNU extension.

‘—max-lines[=MAX-LINES]’ ‘-L MAX-LINES’ ‘-l[MAX-LINES]’ Use at most MAX-LINES nonblank input lines per command line; MAX-LINES defaults to 1 if omitted; omitting the argument is not allowed in the case of the ‘-L’ option. Trailing blanks cause an input line to be logically continued on the next input line, for the purpose of counting the lines. Implies ‘-x’. The preferred name for this option is ‘-L’ as this is specified by POSIX.

‘—max-args=MAX-ARGS’ ‘-n MAX-ARGS’ Use at most MAX-ARGS arguments per command line. Fewer than MAX-ARGS arguments will be used if the size (see the ‘-s’ option) is exceeded, unless the ‘-x’ option is given, in which case ‘xargs’ will exit.

‘—max-chars=MAX-CHARS’ ‘-s MAX-CHARS’ Use at most MAX-CHARS characters per command line, including the command initial arguments and the terminating nulls at the ends of the argument strings. If you specify a value for this option which is too large or small, a warning message is printed and the appropriate upper or lower limit is used instead. You can use ‘—show-limits’ option to understand the command-line limits applying to ‘xargs’ and how this is affected by any other options. The POSIX limits shown when you do this have already been adjusted to take into account the size of your environment variables. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128KiB, 128Kib is used as the default value; otherwise, the default value is the maximum.

3.3.2.5 Controlling Parallelism

Normally, ‘xargs’ runs one command at a time. This is called “serial” execution; the commands happen in a series, one after another. If you’d like ‘xargs’ to do things in “parallel”, you can ask it to do so, either when you invoke it, or later while it is running. Running several commands at one time can make the entire operation go more quickly, if the commands are independent, and if your system has enough resources to handle the load. When parallelism works in your application, ‘xargs’ provides an easy way to get your work done faster.

‘—max-procs=MAX-PROCS’ ‘-P MAX-PROCS’ Run up to MAX-PROCS processes at a time; the default is 1. If MAX-PROCS is 0, ‘xargs’ will run as many processes as possible at a time. Use the ‘-n’, ‘-s’, or ‘-L’ option with ‘-P’; otherwise chances are that the command will be run only once. For example, suppose you have a directory tree of large image files and a ‘makeallsizes’ script that takes a single file name and creates various sized images from it (thumbnail-sized, web-page-sized, printer-sized, and the original large file). The script is doing enough work that it takes significant time to run, even on a single image. You could run: find originals -name ’.jpg’ | xargs -l makeallsizes This will run ‘makeallsizes FILENAME’ once for each ‘.jpg’ file in the ‘originals’ directory. However, if your system has two central processors, this script will only keep one of them busy. Instead, you could probably finish in about half the time by running: find originals -name ’.jpg’ | xargs -l -P 2 makeallsizes ‘xargs’ will run the first two commands in parallel, and then whenever one of them terminates, it will start another one, until the entire job is done. The same idea can be generalized to as many processors as you have handy. It also generalizes to other resources besides processors. For example, if ‘xargs’ is running commands that are waiting for a response from a distant network connection, running a few in parallel may reduce the overall latency by overlapping their waiting time. If you are running commands in parallel, you need to think about how they should arbitrate access to any resources that they share. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don’t want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). ‘xargs’ also allows “turning up” or “turning down” its parallelism in the middle of a run. Suppose you are keeping your four-processor system busy for hours, processing thousands of images using ‘-P 4’. Now, in the middle of the run, you or someone else wants you to reduce your load on the system, so that something else will run faster. If you interrupt ‘xargs’, your job will be half-done, and it may take significant manual work to resume it only for the remaining images. If you suspend ‘xargs’ using your shell’s job controls (e.g. ‘control-Z’), then it will get no work done while suspended. Find out the process ID of the ‘xargs’ process, either from your shell or with the ‘ps’ command. After you send it the signal ‘SIGUSR2’, ‘xargs’ will run one fewer command in parallel. If you send it the signal ‘SIGUSR1’, it will run one more command in parallel. For example: shell xargs <allimages -l -P 4 makeallsizes & [4] 27643 ... at some later point ... shell kill -USR2 27643 shell$ kill -USR2 %4 The first ‘kill’ command will cause ‘xargs’ to wait for two commands to terminate before starting the next command (reducing the parallelism from 4 to 3). The second ‘kill’ will reduce it from 3 to 2. (‘%4’ works in some shells as a shorthand for the process ID of the background job labeled ‘[4]’.) Similarly, if you started a long ‘xargs’ job without parallelism, you can easily switch it to start running two commands in parallel by sending it a ‘SIGUSR1’. ‘xargs’ will never terminate any existing commands when you ask it to run fewer processes. It merely waits for the excess commands to finish. If you ask it to run more commands, it will start the next one immediately (if it has more work to do). If the degree of parallelism is already 1, sending ‘SIGUSR2’ will have no further effect (since ‘—max-procs=0’ means that there should be no limit on the number of processes to run). There is an implementation-defined limit on the number of processes. This limit is shown with ‘xargs —show-limits’. The limit is at least 127 on all systems (and on the author’s system it is 2147483647). If you send several identical signals quickly, the operating system does not guarantee that each of them will be delivered to ‘xargs’. This means that you can’t rapidly increase or decrease the parallelism by more than one command at a time. You can avoid this problem by sending a signal, observing the result, then sending the next one; or merely by delaying for a few seconds between signals (unless your system is very heavily loaded). Whether or not parallel execution will work well for you depends on the nature of the commmand you are running in parallel, on the configuration of the system on which you are running the command, and on the other work being done on the system at the time.

3.3.2.6 Interspersing File Names

‘xargs’ can insert the name of the file it is processing between arguments you give for the command. Unless you also give options to limit the command size (*note Limiting Command Size::), this mode of operation is equivalent to ‘find -exec’ (*note Single File::).

Option:

—replace[=REPLACE-STR] -I REPLACE-STR -i REPLACE-STR

Replace occurrences of REPLACE-STR in the initial arguments with names read from the input. Also, unquoted blanks do not terminate arguments; instead, the input is split at newlines only. For the -i option, if REPLACE-STR is omitted for --replace or -i, it defaults to {} (like for find -exec). Implies -x and -l 1. -i is deprecated in favour of -I. As an example, to sort each file in the bills directory, leaving the output in that file name with .sorted appended, you could do:

find bills -type f | xargs -I XX sort -o XX.sorted XX

The equivalent command using find -execdir is:

find bills -type f -execdir sort -o '{}.sorted' '{}' ';'

When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option.

To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur.

For example:

somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}'

Here, the first invocation of xargs has no input line length limit because it doesn’t use the -I option.

The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle.

This is not an ideal solution.

Instead, the -I option should not impose a line length limit (apart from any limit imposed by the operating system) and so one might consider this limitation to be a bug.

A better solution would be to allow xargs -I to automatically move to a larger value for the -s option when this is needed.

This sort of problem doesn’t occur with the output of find because it emits just one filename per line.

3.3.3 Querying

To ask the user whether to execute a command on a single file, you can use the find primary -okdir instead of -execdir, and the find primary -ok instead of -exec:

-okdir command

Like -execdir (*note Single File::), but ask the user first. If the user does not agree to run the command, just return false. Otherwise, run it, with standard input redirected from /dev/null.

This action may not be specified together with the -files0-from option.

The response to the prompt is matched against a pair of regular expressions to determine if it is a yes or no response. These regular expressions are obtained from the system (nl_langinfo items YESEXPR and NOEXPR are used) if the POSIXLY_CORRECT environment variable is set and the system has such patterns available. Otherwise, find’s message translations are used. In either case, the LC_MESSAGES environment variable will determine the regular expressions used to determine if the answer is affirmative or negative. The interpretation of the regular expressions themselves will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes).

!tip Action:

-ok command ;

This insecure variant of the -okdir action is specified by POSIX. The main difference is that the command is executed in the directory from which find was invoked, meaning that {} is expanded to a relative path starting with the name of one of the starting directories, rather than just the basename of the matched file. If the command is run, its standard input is redirected from /dev/null.

This action may not be specified together with the -files0-from option.

When processing multiple files with a single command, to query the user you give ‘xargs’ the following option. When using this option, you might find it useful to control the number of files processed per invocation of the command (*note Limiting Command Size::).

‘—interactive’ ‘-p’ Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with ‘y’ or ‘Y’. Implies ‘-t’.

3.4 Delete Files

— Action: -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and ‘find”s exit status will be nonzero (when it eventually exits).

Warning: Don’t forget that ‘find’ evaluates the command line as an expression, so putting ‘-delete’ first will make ‘find’ try to delete everything below the starting points you specified.

The use of the ‘-delete’ action on the command line automatically turns on the ‘-depth’ option. As in turn ‘-depth’ makes ‘-prune’ ineffective, the ‘-delete’ action cannot usefully be combined with ‘-prune’.

Often, the user might want to test a ‘find’ command line with ‘-print’ prior to adding ‘-delete’ for the actual removal run. To avoid surprising results, it is usually best to remember to use ‘-depth’ explicitly during those earlier test runs.

See *note Cleaning Up:: for a deeper discussion about good use cases of the ‘-delete’ action and those with surprising results.

The ‘-delete’ action will fail to remove a directory unless it is empty.

Together with the ‘-ignore_readdir_race’ option, ‘find’ will ignore errors of the ‘-delete’ action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the ‘-delete’ action will be true.

3.5 Adding Tests

You can test for file attributes that none of the ‘find’ builtin tests check. To do this, use ‘xargs’ to run a program that filters a list of files printed by ‘find’.

If possible, use ‘find’ builtin tests to pare down the list, so the program run by ‘xargs’ has less work to do. The tests builtin to ‘find’ will likely run faster than tests that other programs perform.

For reasons of efficiency it is often useful to limit the number of times an external program has to be run. For this reason, it is often a good idea to implement “extended” tests by using ‘xargs’.

For example, here is a way to print the names of all of the unstripped binaries in the ‘/usr/local’ directory tree. Builtin tests avoid running ‘file’ on files that are not regular files or are not executable.

find /usr/local -type f -perm /a=x | xargs file |
   grep 'not stripped' | cut -d: -f1

The cut program removes everything after the file name from the output of file.

However, using xargs can present important security problems (*note Security Considerations::). These can be avoided by using -execdir. The -execdir action is also a useful way of putting your own test in the middle of a set of other tests or actions for find (for example, you might want to use -prune).

To place a special test somewhere in the middle of a find expression, you can use -execdir (or, less securely, -exec) to run a program that performs the test.

Because -execdir evaluates to the exit status of the executed program, you can use a program (which can be a shell script) that tests for a special attribute and make it exit with a true (zero) or false (non-zero) status.

It is a good idea to place such a special test after the builtin tests, because it starts a new process which could be avoided if a builtin test evaluates to false.

here is a shell script called unstripped that checks whether its argument is an unstripped binary file:

#! /bin/sh
file "$1" | grep -q "not stripped"

This script relies on the shell exiting with the status of the last command in the pipeline, in this case grep.

The grep command exits with a true status if it found any matches, false if not. Here is an example of using the script (assuming it is in your search path).

It lists the stripped executables (and shell scripts) in the file sbins and the unstripped ones in ubins.

find /usr/local -type f -perm /a=x \
    \( -execdir unstripped '{}' \; -fprint ubins -o -fprint sbins \)