find
locate
updatedb
xargs
find Primary Index
This file documents the GNU utilities for finding files that match certain criteria and performing various operations on them.
Copyright (C) 1994, 1996, 1998, 2000, 2001, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License.”
This file documents the GNU utilities for finding files that match certain criteria and performing various actions on them.
This is edition 4.4.0, for find version 4.4.0.
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!
To report a bug in GNU findutils, please use the form on the Savannah
web site at
http://savannah.gnu.org/bugs/?group=findutils. Reporting bugs
this way means that you will then be able to track progress in fixing
the problem.
If you don't have web access, you can also just send mail to the mailing list. The mailing list bug-findutils@gnu.org carries discussion of bugs in findutils, questions and answers about the software and discussion of the development of the programs. To join the list, send email to bug-findutils-request@gnu.org.
Please read any relevant sections of this manual before asking for
help on the mailing list. You may also find it helpful to read the
NON-BUGS section of the find manual page.
If you ask for help on the mailing list, people will be able to help you much more effectively if you include the following things:
It may also be the case that the bug you are describing has already been fixed, if it is a bug. Please check the most recent findutils releases at ftp://ftp.gnu.org/gnu/findutils and, if possible, the development branch at ftp://alpha.gnu.org/gnu/findutils. If you take the time to check that your bug still exists in current releases, this will greatly help people who want to help you solve your problem. Please also be aware that if you obtained findutils as part of the GNU/Linux 'distribution', the distributions often lag seriously behind findutils releases, even the stable release. Please check the GNU FTP site.
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:
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:
This manual describes how to perform each of those tasks, and more.
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 searches for files in a directory hierarchy and prints
information about the files it found. It is run like this:
find [file...] [expression]
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 Kilobytes.
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.
locate searches special file name databases for file names that
match patterns. The system administrator runs the updatedb
program to create the databases. locate is run like this:
locate [option...] pattern...
This example prints the names of all files in the default file name
database whose name ends with ‘Makefile’ or ‘makefile’.
Which file names are stored in the database depends on how the system
administrator ran updatedb.
locate '*[Mm]akefile'
The name xargs, pronounced EX-args, means “combine
arguments.” xargs builds and executes command lines by
gathering together arguments it reads on the standard input. Most
often, these arguments are lists of file names generated by
find. xargs is run like this:
xargs [option...] [command [initial-arguments]]
The following command searches the files listed in the file file-list and prints all of the lines in them that contain the word ‘typedef’.
xargs grep typedef < file-list
find ExpressionsThe 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:
You can omit the operator between two primaries; it defaults to ‘-and’. See Combining Primaries With Operators, for ways to connect primaries into more complex expressions. If the expression contains no actions other than ‘-prune’, ‘-print’ is performed on all files for which the entire expression is true (see Print File Name).
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-nBy default, find prints to the standard output the names of the
files that match the given criteria. See Actions, for how to get
more information about the matching files.
Here are ways to search for files whose name matches a certain pattern. See 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.
True if the base of the file name (the path with the leading directories removed) matches shell pattern pattern. For ‘-iname’, the match is case-insensitive.1 To ignore a whole directory tree, use ‘-prune’ (see 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’ will match a file name with a leading ‘.’. For example the command ‘find /tmp -name \*bar’ will 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.
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 (see Directories). The “entire file name” as used by
findstarts with the starting-point specified on the command line, and is not converted to an absolute pathname, so for examplecd /; find tmp -wholename /tmpwill never match anything. The name ‘-wholename’ is GNU-specific, but ‘-path’ is more portable; it is supported by HP-UXfindand will soon be part of POSIX.
These tests are like ‘-wholename’ and ‘-path’, but the match is case-insensitive.
In the context of the tests ‘-path’, ‘-wholename’,
‘-ipath’ and ‘-wholename’, 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
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’. See Syntax of Regular Expressions, for a description of the syntax of regular expressions. For ‘-iregex’, the match is case-insensitive. 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’.
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
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. See 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
(see 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 pathLOCATE_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. See 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. See Invoking updatedb, for a
description of its ‘--dbformat’ and ‘--output’ options.
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.
*?[string]\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
‘foo*bar’ can match a file name ‘foo3/bar’, and a pattern
‘./sr*sc’ 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 :-
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.
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.
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’.
The following differences in behavior occur when the ‘-L’ option is used:
find follows symbolic links to directories when searching
directory trees.
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).
True if the file is a symbolic link whose contents match shell pattern pattern. For ‘-ilname’, the match is case-insensitive. See 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. To find all the names which refer to the same file as NAME, use ‘-samefile NAME’. If you are not using the ‘-L’ option, you can confine your search to one filesystem using the ‘-xdev’ option. This is useful because hard links cannot point outside a single filesystem, so this can cut down on needless searching.
If the ‘-L’ option is in effect, and NAME is in fact a symbolic link, the symbolic link will be dereferenced. Hence you are searching for other links (hard or symbolic) to the file pointed to by NAME. If ‘-L’ is in effect but NAME is not itself a symbolic link, other symbolic links to the file NAME will be matched.
You can also search for files by inode number. This can occasionally
be useful in diagnosing problems with filesystems for example, because
fsck tends to print inode numbers. Inode numbers also
occasionally turn up in log messages for some types of software, and
are used to support the ftok() library function.
You can learn a file's inode number and the number of links to it by running ‘ls -li’ or ‘find -ls’.
You can search for hard links to inode number NUM by using ‘-inum NUM’. If there are any filesystem 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’ this saves needless searching, since hard links to a file must be on the same filesystem. See Filesystems.
File is a hard link to the same inode as NAME. If the ‘-L’ option is in effect, symbolic links to the same file as NAME points to are also matched.
File has inode number n. The ‘+’ and ‘-’ qualifiers also work, though these are rarely useful. Much of the time it is easier to use ‘-samefile’ rather than this option.
You can also search for files that have a certain number of links,
with ‘-links’. Directories normally have at least two hard
links; their . entry is the second one. If they have
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.
Each file has three time stamps, which record the last time that certain operations were performed on the file:
Some systems also provide a timestamp that indicates when a file was created. For example, the UFS2 fileystem 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 time stamps are within a certain age range, or compare them to other time stamps.
These tests are mainly useful with ranges (‘+n’ and ‘-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.
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
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 1The ‘-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.
Succeeds if timestamp ‘X’ of the file being considered is newer than timestamp ‘Y’ of the file reference. The latters ‘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. See 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/foosucceeds 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,
findexits 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-falsedoes).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$$
find /usr -newer /tmp/stamp$$
rm -f /tmp/stamp$$
True if the file was last accessed (or its status changed, or it was modified) more recently than file was modified. These tests are affected by ‘-follow’ only if ‘-follow’ comes before them on the command line. See 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
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.
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
k- kilobytes (1024 bytes)
w- 2-byte words
M- Megabytes (units of 1048576 bytes)
G- Gigabytes (units of 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. There is no `=' prefix, because that's the default anyway.
The size does not count indirect blocks, but it does count blocks in sparse files that are not actually allocated. In other words, it's consistent with the result you get for ‘ls -l’ or ‘wc -c’. This handling of sparse files differs from the output of the ‘%k’ and ‘%b’ format specifiers for the ‘-printf’ predicate.
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’ (see Directories) and ‘-delete’ (see Single File).
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)
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.
See Symbolic Links, for more information on ‘-follow’ and ‘-L’.
True if the file is owned by user uname (belongs to group gname). A numeric ID is allowed.
True if the file's numeric user ID (group ID) is n. These tests support ranges (‘+n’ and ‘-n’), unlike ‘-user’ and ‘-group’.
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
chownorchgrpprogram.
See 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.
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.
True if the file's mode bits match pmode, which can be either a symbolic or numeric mode (see File Permissions) optionally prefixed by ‘-’ or ‘/’.
A pmode that starts with neither ‘-’ nor ‘/’ matches if mode exactly matches the file mode bits.
A pmode that starts with ‘+’ but which is not valid (for example ‘+a+x’) is an error if the POSIXLY_CORRECT environment variable it set. Otherwise this is treated as if the initial ‘+’ were a ‘/’, for backward compatibility.
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 either their owner or their group. The files don't have to be writable by both the owner and group 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 owner and their group.
- ‘-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.
- ‘-perm -g+w,o+w’
- 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 GNUfindprior to 4.3.3 matched no files in this situation.
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.
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.
Descend at most levels (a non-negative integer) levels of directories below the command line arguments. ‘-maxdepth 0’ means only apply the tests and actions to the command line arguments.
Do not apply any tests or actions at levels less than levels (a non-negative integer). ‘-mindepth 1’ means process all files except the command line arguments.
Process each directory's contents before the directory itself. Doing this is a good idea when producing lists of files to archive with
cpioortar. If a directory does not have write permission for its owner, its contents can still be restored from the archive since the directory's permissions are restored after its contents.
This is a deprecated synonym for ‘-depth’, for compatibility with Mac OS X, FreeBSD and OpenBSD. The ‘-depth’ option is a POSIX feature, so it is better to use that.
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 -printThe 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 -printor use the comma operator:
find . -wholename './src/emacs' -prune , -printIf 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.
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, whilt ‘-quit’ simply makes
findstop immediately. No child processes will be left running, but no more files specified on the command line will be processed. For example,find /tmp/foo /tmp/bar -print -quitwill print only ‘/tmp/foo’. Any command lines which have been built by ‘-exec ... \+’ or ‘-execdir ... \+’ are invoked before the program is exited.
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
findis 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.
If a file disappears after its name has been read from a directory but before
findgets around to examining the file withstat, don't issue an error message. If you don't specify this option, an error message will be issued. 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 fromfindis 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.
This option reverses the effect of the ‘-ignore_readdir_race’ option.
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:
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:
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:
ext2 ext3 proc sysfs ufs 4.2 4.3 nfs tmp mfs S51K S52KYou can use ‘-printf’ with the ‘%F’ directive to see the types of your filesystems. The ‘%D’ directive shows the device number. See Print File Information. ‘-fstype’ is usually used with ‘-prune’ to avoid searching remote filesystems (see Directories).
Operators build a complex expression from tests and actions. The operators are, in order of decreasing precedence:
( expr )! expr-not expr -a expr2 -and expr2 -o expr2 -or expr2 , expr2find 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:
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.
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.
True; print the entire file name into file file, followed by a newline. If file does not exist when
findis 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.
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-quotesThe fields are:
- The inode number of the file. See Hard Links, for how to find files based on their inode number.
- the number of blocks in the file. The block counts are of 1K blocks, unless the environment variable
POSIXLY_CORRECTis set, in which case 512-byte blocks are used. See Size, for how to find files based on their size.- 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 (see 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. See File Permissions, for more details about file permissions. See Mode Bits, for how to find files based on their file mode bits.
- The number of hard links to the file.
- The user who owns the file.
- The file's group.
- The file's size in bytes.
- The date the file was last modified.
- 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’.
True; like ‘-ls’ but write to file like ‘-fprint’ (see Print File Name). The named output file is always created, even if no output is sent to it.
True; print format on the standard output, interpreting ‘\’ escapes and ‘%’ directives. Field widths and precisions can be specified as with the
printfC 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’.
True; like ‘-printf’ but write to file like ‘-fprint’ (see Print File Name). The output file is always created, even if no output is ever sent to it.
The escapes that ‘-printf’ and ‘-fprintf’ recognise are:
\a\b\c\f\n\r\t\v\\\0\NNNA ‘\’ 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).
‘-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. A ‘%’ character followed by
an 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.
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.
%pfind - that is, as a relative path from
one of the starting points).
%f%h%P%H%g%G%u%U%mThe 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.
%Mls). This
directive is supported in findutils 4.2.5 and later.
%k%b%s%S(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.
%d%Dst_dev field of
struct stat), in decimal.
%F%l%i%n%y%YSome 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
%actime
function.
%Ak%cctime function.
%Ck%tctime function.
%TkBelow are the formats for the directives ‘%A’, ‘%C’, and
‘%T’, which print the file's timestamps. Some of these formats
might not be available on all systems, due to differences in the C
strftime function between systems.
The following format directives print single components of the time.
HIklpZMS@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.
The following format directives print single components of the date.
aAbhBmdwjUWYyThe following format directives print combinations of time and date components.
rTXcDx+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.
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.
Here is how to run a command on one file at a time.
Execute command; true if zero status is returned.
findtakes all arguments after ‘-exec’ 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 in whichfindwas run.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:
Another similar option, ‘-exec’ is supported, but is less secure. See Security Considerations, for a discussion of the security problems surrounding ‘-exec’.
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
findwas 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
findreplace the ‘{}’ only where it appears on its own in an argument, GNUfindreplaces ‘{}’ wherever it appears.
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.
This works as for ‘-execdir command ;’, except that 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 &ls