사용 버전 : Linux 우분투(레드햇 계열) 24.04.01 LTS 버전
사용한 시스템 지역/언어 : 대한민국/한글
man find 원문
FIND(1) General Commands Manual FIND(1)
NAME
find - search for files in a directory hierarchy
SYNOPSIS
find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [ex‐
pression]
DESCRIPTION
This manual page documents the GNU version of find. 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
precedence (see section OPERATORS), 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, `.' is assumed.
If you are using find in an environment where security is important
(for example if you are using it to search directories that are
writable by other users), you should read the `Security Considerations'
chapter of the findutils documentation, which is called Finding Files
and comes with findutils. That document also includes a lot more de‐
tail and discussion than this manual page, so you may find it a more
useful source of information.
OPTIONS
The -H, -L and -P options control the treatment of symbolic links.
Command-line arguments following these are taken to be names of files
or directories to be examined, up to the first argument that begins
with `-', or the argument `(' or `!'. That argument and any following
arguments are taken to be the expression describing what is to be
searched for. If no paths are given, the current directory is used.
If no expression is given, the expression -print is used (but you
should probably consider using -print0 instead, anyway).
This manual page talks about `options' within the expression list.
These options control the behaviour of find but are specified immedi‐
ately after the last path name. The five `real' options -H, -L, -P, -D
and -O must appear before the first path name, if at all. A double
dash -- could theoretically be used to signal that any remaining argu‐
ments are not options, but this does not really work due to the way
find determines the end of the following path arguments: it does that
by reading until an expression argument comes (which also starts with a
`-'). Now, if a path argument would start 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 du‐
bious path names with either `./' or to use absolute path names start‐
ing with '/'. Alternatively, it is generally safe though non-portable
to use the GNU option -files0-from to pass arbitrary starting points to
find.
-P Never follow symbolic links. This is the default behaviour.
When find examines or prints information about files, and the
file is a symbolic link, the information used shall be taken
from the properties of the symbolic link itself.
-L Follow symbolic links. When find examines or prints information
about files, the information used shall be taken from the prop‐
erties of the file to which the link points, not from the link
itself (unless it is a broken symbolic link or find is unable to
examine the file to which the link points). Use of this option
implies -noleaf. If you later use the -P option, -noleaf will
still be in effect. If -L is in effect and find discovers a
symbolic link to a subdirectory during its search, the subdirec‐
tory pointed to by the symbolic link will be searched.
When the -L option is in effect, the -type predicate will always
match against the type of the file that a symbolic link points
to rather than the link itself (unless the symbolic link is bro‐
ken). Actions that can cause symbolic links to become broken
while find is executing (for example -delete) can give rise to
confusing behaviour. Using -L causes the -lname and -ilname
predicates always to return false.
-H Do not follow symbolic links, except while processing the com‐
mand line arguments. When find examines or prints information
about files, the information used shall be taken from the prop‐
erties of the symbolic link itself. The only exception to this
behaviour is when a file specified on the command line is a sym‐
bolic link, and the link can be resolved. For that situation,
the information used is taken from whatever the link points to
(that is, the link is followed). The information about the link
itself is used as a fallback if the file pointed to by the sym‐
bolic link cannot be examined. If -H is in effect and one of
the paths specified on the command line is a symbolic link to a
directory, the contents of that directory will be examined
(though of course -maxdepth 0 would prevent this).
If more than one of -H, -L and -P is specified, each overrides the oth‐
ers; the last one appearing on the command line takes effect. Since it
is the default, the -P option should be considered to be in effect un‐
less either -H or -L is specified.
GNU find frequently stats files during the processing of the command
line itself, before any searching has begun. These options also affect
how those arguments are processed. Specifically, there are a number of
tests that compare files listed on the command line against a file we
are currently considering. In each case, the file specified on the
command line will have been examined and some of its properties will
have been saved. If the named file is in fact a symbolic link, and the
-P option is in effect (or if neither -H nor -L were specified), the
information used for the comparison will be taken from the properties
of the symbolic link. Otherwise, it will be taken from the properties
of the file the link points to. If find cannot follow the link (for
example because it has insufficient privileges or the link points to a
nonexistent file) the properties of the link itself will be used.
When the -H or -L options are in effect, any symbolic links listed as
the argument of -newer will be dereferenced, and the timestamp will be
taken from the file to which the symbolic link points. The same con‐
sideration applies to -newerXY, -anewer and -cnewer.
The -follow option has a similar effect to -L, though it takes effect
at the point where it appears (that is, if -L is not used but -follow
is, any symbolic links appearing after -follow on the command line will
be dereferenced, and those before it will not).
-D debugopts
Print diagnostic information; this can be helpful to diagnose
problems with why find is not doing what you want. The list of
debug options should be comma separated. Compatibility of the
debug options is not guaranteed between releases of findutils.
For a complete list of valid debug options, see the output of
find -D help. Valid debug options include
exec Show diagnostic information relating to -exec, -execdir,
-ok and -okdir
opt Prints diagnostic information relating to the optimisa‐
tion of the expression tree; see the -O option.
rates Prints a summary indicating how often each predicate suc‐
ceeded or failed.
search Navigate the directory tree verbosely.
stat Print messages as files are examined with the stat and
lstat system calls. The find program tries to minimise
such calls.
tree Show the expression tree in its original and optimised
form.
all Enable all of the other debug options (but help).
help Explain the debugging options.
-Olevel
Enables query optimisation. The find program reorders tests to
speed up execution while preserving the overall effect; that is,
predicates with side effects are not reordered relative to each
other. The optimisations performed at each optimisation level
are as follows.
0 Equivalent to optimisation level 1.
1 This is the default optimisation level and corresponds to
the traditional behaviour. Expressions are reordered so
that tests based only on the names of files (for example
-name and -regex) are performed first.
2 Any -type or -xtype tests are performed after any tests
based only on the names of files, but before any tests
that require information from the inode. On many modern
versions of Unix, file types are returned by readdir()
and so these predicates are faster to evaluate than pred‐
icates which need to stat the file first. If you use the
-fstype FOO predicate and specify a filesystem type FOO
which is not known (that is, present in `/etc/mtab') at
the time find starts, that predicate is equivalent to
-false.
3 At this optimisation level, the full cost-based query op‐
timiser is enabled. The order of tests is modified so
that cheap (i.e. fast) tests are performed first and more
expensive ones are performed later, if necessary. Within
each cost band, predicates are evaluated earlier or later
according to whether they are likely to succeed or not.
For -o, predicates which are likely to succeed are evalu‐
ated earlier, and for -a, predicates which are likely to
fail are evaluated earlier.
The cost-based optimiser has a fixed idea of how likely any
given test is to succeed. In some cases the probability takes
account of the specific nature of the test (for example, -type f
is assumed to be more likely to succeed than -type c). The
cost-based optimiser is currently being evaluated. If it does
not actually improve the performance of find, it will be removed
again. Conversely, optimisations that prove to be reliable, ro‐
bust and effective may be enabled at lower optimisation levels
over time. However, the default behaviour (i.e. optimisation
level 1) will not be changed in the 4.3.x release series. The
findutils test suite runs all the tests on find at each optimi‐
sation level and ensures that the result is the same.
EXPRESSION
The part of the command line after the list of starting points is the
expression. This is a kind of query specification describing how we
match files and what we do with the files that were matched. An ex‐
pression is composed of a sequence of things:
Tests Tests return a true or false value, usually on the basis of some
property of a file we are considering. The -empty test for ex‐
ample is true only when the current file is empty.
Actions
Actions have side effects (such as printing something on the
standard output) and return either true or false, usually based
on whether or not they are successful. The -print action for
example prints the name of the current file on the standard out‐
put.
Global options
Global options affect the operation of tests and actions speci‐
fied on any part of the command line. Global options always re‐
turn true. The -depth option for example makes find traverse
the file system in a depth-first order.
Positional options
Positional options affect only tests or actions which follow
them. Positional options always return true. The -regextype
option for example is positional, specifying the regular expres‐
sion dialect for regular expressions occurring later on the com‐
mand line.
Operators
Operators join together the other items within the expression.
They include for example -o (meaning logical OR) and -a (meaning
logical AND). Where an operator is missing, -a is assumed.
The -print action is performed on all files for which the whole expres‐
sion is true, unless it 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.
The -delete action also acts like an option (since it implies -depth).
POSITIONAL OPTIONS
Positional options always return true. They affect only tests occur‐
ring later on the command line.
-daystart
Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and
-mtime) from the beginning of today rather than from 24 hours
ago. This option only affects tests which appear later on the
command line.
-follow
Deprecated; use the -L option instead. Dereference symbolic
links. Implies -noleaf. The -follow option affects only those
tests which appear after it on the command line. Unless the -H
or -L option has been specified, the position of the -follow op‐
tion changes the behaviour of the -newer predicate; any files
listed as the argument of -newer will be dereferenced if they
are symbolic links. The same consideration applies to -newerXY,
-anewer and -cnewer. Similarly, the -type predicate will always
match against the type of the file that a symbolic link points
to rather than the link itself. Using -follow causes the -lname
and -ilname predicates always to return false.
-regextype type
Changes the regular expression syntax understood by -regex and
-iregex tests which occur later on the command line. To see
which regular expression types are known, use -regextype help.
The Texinfo documentation (see SEE ALSO) explains the meaning of
and differences between the various types of regular expression.
-warn, -nowarn
Turn warning messages on or off. These warnings apply only to
the command line usage, not to any conditions that find might
encounter when it searches directories. The default behaviour
corresponds to -warn if standard input is a tty, and to -nowarn
otherwise. If a warning message relating to command-line usage
is produced, the exit status of find is not affected. If the
POSIXLY_CORRECT environment variable is set, and -warn is also
used, it is not specified which, if any, warnings will be ac‐
tive.
GLOBAL OPTIONS
Global options always return true. Global options take effect even for
tests which occur earlier on the command line. To prevent confusion,
global options should specified on the command-line after the list of
start points, just before the first test, positional option or action.
If you specify a global option in some other place, find will issue a
warning message explaining that this can be confusing.
The global options occur after the list of start points, and so are not
the same kind of option as -L, for example.
-d A synonym for -depth, for compatibility with FreeBSD, NetBSD,
MacOS X and OpenBSD.
-depth Process each directory's contents before the directory itself.
The -delete action also implies -depth.
-files0-from file
Read the starting points from file instead of getting them on
the command line. In contrast to the known limitations of pass‐
ing starting points via arguments on the command line, namely
the limitation of the amount of file names, and the inherent am‐
biguity of file names clashing with option names, using this op‐
tion 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 addi‐
tionally 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 find‐
utils release to release.
-help, --help
Print a summary of the command-line usage of find and exit.
-ignore_readdir_race
Normally, find will emit an error message when it fails to stat
a file. If you give this option and a file is deleted between
the time find reads the name of the file from the directory and
the time it tries to stat the file, no error message will be is‐
sued. This also applies to files or directories whose names are
given on the command line. This option takes effect at the time
the command line is read, which means that you cannot search one
part of the filesystem with this option on and part of it with
this option off (if you need to do that, you will need to issue
two find commands instead, one with the option and one without
it).
Furthermore, find with the -ignore_readdir_race option will ig‐
nore errors of the -delete action in the case the file has dis‐
appeared since the parent directory was read: it will not output
an error diagnostic, and the return code of the -delete action
will be true.
-maxdepth levels
Descend at most levels (a non-negative integer) levels of direc‐
tories below the starting-points. Using -maxdepth 0 means only
apply the tests and actions to the starting-points themselves.
-mindepth levels
Do not apply any tests or actions at levels less than levels (a
non-negative integer). Using -mindepth 1 means process all
files except the starting-points.
-mount Don't descend directories on other filesystems. An alternate
name for -xdev, for compatibility with some other versions of
find.
-noignore_readdir_race
Turns off the effect of -ignore_readdir_race.
-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 `.' en‐
try. Additionally, its subdirectories (if any) each have a `..'
entry linked to that directory. When find is examining a direc‐
tory, after it has statted 2 fewer subdirectories than the di‐
rectory'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.
-version, --version
Print the find version number and exit.
-xdev Don't descend directories on other filesystems.
TESTS
Some tests, for example -newerXY and -samefile, allow comparison be‐
tween the file currently being examined and some reference file speci‐
fied on the command line. When these tests are used, the interpreta‐
tion of the reference file is determined by the options -H, -L and -P
and any previous -follow, but the reference file is only examined once,
at the time the command line is parsed. If the reference file cannot
be examined (for example, the stat(2) system call fails for it), an er‐
ror message is issued, and find exits with a nonzero status.
A numeric argument n can be specified to tests (like -amin, -mtime,
-gid, -inum, -links, -size, -uid and -used) as
+n for greater than n,
-n for less than n,
n for exactly n.
Supported tests:
-amin n
File was last accessed less than, more than or exactly n minutes
ago.
-anewer reference
Time of the last access of the current file is more recent than
that of the last data modification of the reference file. 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.
-atime n
File was last accessed less than, more than or exactly n*24
hours ago. When find figures out how many 24-hour periods ago
the file was last accessed, any fractional part is ignored, so
to match -atime +1, a file has to have been accessed at least
two days ago.
-cmin n
File's status was last changed less than, more than or exactly n
minutes ago.
-cnewer reference
Time of the last status change of the current file is more re‐
cent than that of the last data modification of the reference
file. If reference is a symbolic link and the -H option or the
-L option is in effect, then the time of the last data modifica‐
tion of the file it points to is always used.
-ctime n
File's status was last changed less than, more than or exactly
n*24 hours ago. See the comments for -atime to understand how
rounding affects the interpretation of file status change times.
-empty File is empty and is either a regular file or a directory.
-executable
Matches files which are executable and directories which are
searchable (in a file name resolution sense) by the current
user. This takes into account access control lists and other
permissions artefacts which the -perm test ignores. This test
makes use of the access(2) system call, and so can be fooled by
NFS servers which do UID mapping (or root-squashing), since many
systems implement access(2) in the client's kernel and so cannot
make use of the UID mapping information held on the server. Be‐
cause this test is based only on the result of the access(2)
system call, there is no guarantee that a file for which this
test succeeds can actually be executed.
-false Always false.
-fstype type
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: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can
use -printf with the %F directive to see the types of your
filesystems.
-gid n File's numeric group ID is less than, more than or exactly n.
-group gname
File belongs to group gname (numeric group ID allowed).
-ilname pattern
Like -lname, but the match is case insensitive. If the -L op‐
tion or the -follow option is in effect, this test returns false
unless the symbolic link is broken.
-iname pattern
Like -name, but the match is case insensitive. For example, the
patterns `fo*' and `F??' match the file names `Foo', `FOO',
`foo', `fOo', etc. The pattern `*foo*` will also match a file
called '.foobar'.
-inum n
File has inode number smaller than, greater than or exactly n.
It is normally easier to use the -samefile test instead.
-ipath pattern
Like -path. but the match is case insensitive.
-iregex pattern
Like -regex, but the match is case insensitive.
-iwholename pattern
See -ipath. This alternative is less portable than -ipath.
-links n
File has less than, more than or exactly n hard links.
-lname pattern
File is a symbolic link whose contents match shell pattern pat‐
tern. The metacharacters do not treat `/' or `.' specially. If
the -L option or the -follow option is in effect, this test re‐
turns false unless the symbolic link is broken.
-mmin n
File's data was last modified less than, more than or exactly n
minutes ago.
-mtime n
File's data was last modified less than, more than or exactly
n*24 hours ago. See the comments for -atime to understand how
rounding affects the interpretation of file modification times.
-name pattern
Base of file name (the path with the leading directories re‐
moved) matches shell pattern pattern. Because the leading di‐
rectories 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). A
warning is issued if you try to do this, unless the environment
variable POSIXLY_CORRECT is set. The metacharacters (`*', `?',
and `[]') match a `.' at the start of the base name (this is a
change in findutils-4.2.2; see section STANDARDS CONFORMANCE be‐
low). To ignore a directory and the files under it, use -prune
rather than checking every file in the tree; see an example in
the description of that action. Braces are not recognised as
being special, despite the fact that some shells including Bash
imbue braces with a special meaning in shell patterns. The
filename matching is performed with the use of the fnmatch(3)
library function. Don't forget to enclose the pattern in quotes
in order to protect it from expansion by the shell.
-newer reference
Time of the last data modification of the current file is more
recent than that of the last data modification of the reference
file. If reference is a symbolic link and the -H option or the
-L option is in effect, then the time of the last data modifica‐
tion of the file it points to is always used.
-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 The access time of the file reference
B The birth time of the file reference
c The inode status change time of reference
m The modification time of the file reference
t reference is interpreted directly as a time
Some combinations are invalid; for example, it is invalid for X
to be t. Some combinations are not implemented on all systems;
for example B is not supported on all systems. If an invalid or
unsupported combination of XY is specified, a fatal error re‐
sults. Time specifications are interpreted as for the argument
to the -d option of GNU date. If you try to use the birth time
of a reference file, and the birth time cannot be determined, a
fatal error message results. If you specify a test which refers
to the birth time of files being examined, this test will fail
for any files where the birth time is unknown.
-nogroup
No group corresponds to file's numeric group ID.
-nouser
No user corresponds to file's numeric user ID.
-path pattern
File name matches shell pattern pattern. The metacharacters do
not treat `/' or `.' specially; so, for example,
find . -path "./sr*sc"
will print an entry for a directory called ./src/misc (if one
exists). To ignore a whole directory tree, use -prune rather
than checking every file in the tree. Note that the pattern
match test applies to the whole file name, starting from one of
the start points named on the command line. It would only make
sense to use an absolute path name here if the relevant start
point is also an absolute path. This means that this command
will never match anything:
find bar -path /foo/bar/myfile -print
Find compares the -path argument with the concatenation of a di‐
rectory name and the base name of the file it's examining.
Since the concatenation will never end with a slash, -path argu‐
ments ending in a slash will match nothing (except perhaps a
start point specified on the command line). The predicate -path
is also supported by HP-UX find and is part of the POSIX 2008
standard.
-perm mode
File's permission bits are exactly mode (octal or symbolic).
Since an exact match is required, if you want to use this form
for symbolic modes, you may have to specify a rather complex
mode string. For example `-perm g=w' will only match files
which have mode 0020 (that is, ones for which group write per‐
mission is the only permission 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. See the EX‐
AMPLES section for some illustrative examples.
-perm -mode
All of the permission bits mode are set for the file. Symbolic
modes are accepted in this form, and this is usually the way in
which you would want to use them. You must specify `u', `g' or
`o' if you use a symbolic mode. See the EXAMPLES section for
some illustrative examples.
-perm /mode
Any of the permission bits mode are set for the file. Symbolic
modes are accepted in this form. You must specify `u', `g' or
`o' if you use a symbolic mode. See the EXAMPLES section for
some illustrative examples. If no permission bits in mode are
set, this test matches any file (the idea here is to be consis‐
tent with the behaviour of -perm -000).
-perm +mode
This is no longer supported (and has been deprecated since
2005). Use -perm /mode instead.
-readable
Matches files which are readable by the current user. This
takes into account access control lists and other permissions
artefacts which the -perm test ignores. This test makes use of
the access(2) system call, and so can be fooled by NFS servers
which do UID mapping (or root-squashing), since many systems im‐
plement access(2) in the client's kernel and so cannot make use
of the UID mapping information held on the server.
-regex pattern
File name matches regular expression pattern. 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'. The regular expressions understood
by find are by default Emacs Regular Expressions (except that
`.' matches newline), but this can be changed with the -regex‐
type option.
-samefile name
File refers to the same inode as name. When -L is in effect,
this can include symbolic links.
-size n[cwbkMG]
File uses less than, more than or exactly n units of space,
rounding up. The following suffixes can be used:
`b' for 512-byte blocks (this is the default if no suffix is
used)
`c' for bytes
`w' for two-byte words
`k' for kibibytes (KiB, units of 1024 bytes)
`M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes)
`G' for gibibytes (GiB, units of 1024 * 1024 * 1024 =
1073741824 bytes)
The size is simply the st_size member of the struct stat popu‐
lated 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. Bear in mind that the `%k' and `%b' format speci‐
fiers of -printf handle sparse files differently. The `b' suf‐
fix always denotes 512-byte blocks and never 1024-byte blocks,
which is different to the behaviour of -ls.
The + and - prefixes signify greater than and less than, as
usual; 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.
-true Always true.
-type c
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; this is never true if the -L option or the
-follow option is in effect, unless the symbolic link is
broken. If you want to search for symbolic links when -L
is in effect, use -xtype.
s socket
D door (Solaris)
To search for more than one type at once, you can supply the
combined list of type letters separated by a comma `,' (GNU ex‐
tension).
-uid n File's numeric user ID is less than, more than or exactly n.
-used n
File was last accessed less than, more than or exactly n days
after its status was last changed.
-user uname
File is owned by user uname (numeric user ID allowed).
-wholename pattern
See -path. This alternative is less portable than -path.
-writable
Matches files which are writable by the current user. This
takes into account access control lists and other permissions
artefacts which the -perm test ignores. This test makes use of
the access(2) system call, and so can be fooled by NFS servers
which do UID mapping (or root-squashing), since many systems im‐
plement access(2) in the client's kernel and so cannot make use
of the UID mapping information held on the server.
-xtype c
The same as -type unless the file is a symbolic link. For sym‐
bolic links: if the -H or -P option was specified, true if the
file is a link to a file of type c; if the -L option has been
given, true if c is `l'. In other words, for symbolic links,
-xtype checks the type of the file that -type does not check.
-context pattern
(SELinux only) Security context of the file matches glob pat‐
tern.
ACTIONS
-delete
Delete files or directories; true if removal succeeded. If the
removal failed, an error message is issued and find's exit sta‐
tus 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 in‐
effective, 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.
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 disap‐
peared 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.
-exec command ;
Execute command; true if 0 status is returned. All following
arguments to find are taken to be arguments to the command until
an argument consisting of `;' is encountered. The string `{}'
is replaced by the current file name being processed everywhere
it occurs in the arguments to the command, not just in arguments
where it is alone, as in some versions of find. Both of these
constructions might need to be escaped (with a `\') or quoted to
protect them from expansion by the shell. See the EXAMPLES sec‐
tion for examples of the use of the -exec option. The specified
command is run once for each matched file. The command is exe‐
cuted in the starting directory. There are unavoidable security
problems surrounding use of the -exec action; you should use the
-execdir option instead.
-exec command {} +
This variant of the -exec action runs the specified command on
the selected files, but the command line is built by appending
each selected file name at the end; the total number of invoca‐
tions of the command will be much less than the number of
matched files. The command line is built in much the same way
that xargs builds its command lines. Only one instance of `{}'
is allowed within the command, and it must appear at the end,
immediately before the `+'; it needs to be escaped (with a `\')
or quoted to protect it from interpretation by the shell. The
command is executed in the starting directory. If any invoca‐
tion with the `+' form returns a non-zero value as exit status,
then find returns a non-zero exit status. If find encounters an
error, this can sometimes cause an immediate exit, so some pend‐
ing commands may not be run at all. For this reason -exec my-
command ... {} + -quit may not result in my-command actually be‐
ing run. This variant of -exec always returns true.
-execdir command ;
-execdir command {} +
Like -exec, but the specified command is run from the subdirec‐
tory containing the matched file, which is not normally the di‐
rectory in which you started find. As with -exec, the {} should
be quoted if find is being invoked from a shell. This a much
more secure method for invoking commands, as it avoids race con‐
ditions during resolution of the paths to the matched files. As
with the -exec action, the `+' form of -execdir will build a
command line to process more than one matched file, but any
given invocation of command will only list files that exist in
the same subdirectory. If you use this option, you must ensure
that your PATH environment variable does not reference `.'; oth‐
erwise, an attacker can run any commands they like by leaving an
appropriately-named file in a directory in which you will run
-execdir. The same applies to having entries in PATH which are
empty or which are not absolute directory names. If any invoca‐
tion with the `+' form returns a non-zero value as exit status,
then find returns a non-zero exit status. If find encounters an
error, this can sometimes cause an immediate exit, so some pend‐
ing commands may not be run at all. The result of the action
depends on whether the + or the ; variant is being used; -ex‐
ecdir command {} + always returns true, while -execdir com‐
mand {} ; returns true only if command returns 0.
-fls file
True; like -ls but write to file like -fprint. The output file
is always created, even if the predicate is never matched. See
the UNUSUAL FILENAMES section for information about how unusual
characters in filenames are handled.
-fprint file
True; print the full file name into file file. If file does not
exist when find is run, it is created; if it does exist, it is
truncated. The file names /dev/stdout and /dev/stderr are han‐
dled specially; they refer to the standard output and standard
error output, respectively. The output file is always created,
even if the predicate is never matched. See the UNUSUAL FILE‐
NAMES section for information about how unusual characters in
filenames are handled.
-fprint0 file
True; like -print0 but write to file like -fprint. The output
file is always created, even if the predicate is never matched.
See the UNUSUAL FILENAMES section for information about how un‐
usual characters in filenames are handled.
-fprintf file format
True; like -printf but write to file like -fprint. The output
file is always created, even if the predicate is never matched.
See the UNUSUAL FILENAMES section for information about how un‐
usual characters in filenames are handled.
-ls True; list current file in ls -dils format on standard output.
The block counts are of 1 KB blocks, unless the environment
variable POSIXLY_CORRECT is set, in which case 512-byte blocks
are used. See the UNUSUAL FILENAMES section for information
about how unusual characters in filenames are handled.
-ok command ;
Like -exec but ask the user first. If the user agrees, run the
command. Otherwise just return false. 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.
The response to the prompt is matched against a pair of regular
expressions to determine if it is an affirmative or negative re‐
sponse. This regular expression is obtained from the system if
the POSIXLY_CORRECT environment variable is set, or otherwise
from find's message translations. If the system has no suitable
definition, find's own definition will be used. In either case,
the interpretation of the regular expression itself will be af‐
fected by the environment variables LC_CTYPE (character classes)
and LC_COLLATE (character ranges and equivalence classes).
-okdir command ;
Like -execdir but ask the user first in the same way as for -ok.
If the user does not agree, just return false. If the command
is run, its standard input is redirected from /dev/null. This
action may not be specified together with the -files0-from op‐
tion.
-print True; print the full file name on the standard output, followed
by a newline. If you are piping the output of find into another
program and there is the faintest possibility that the files
which you are searching for might contain a newline, then you
should seriously consider using the -print0 option instead of
-print. See the UNUSUAL FILENAMES section for information about
how unusual characters in filenames are handled.
-print0
True; print the full file name on the standard output, followed
by a null character (instead of the newline character that
-print uses). This allows file names that contain newlines or
other types of white space to be correctly interpreted by pro‐
grams that process the find output. This option corresponds to
the -0 option of xargs.
-printf format
True; print format on the standard output, interpreting `\' es‐
capes and `%' directives. Field widths and precisions can be
specified as with the printf(3) C function. Please note that
many of the fields are printed as %s rather than %d, and this
may mean that flags don't work as you might expect. This also
means that the `-' flag does work (it forces fields to be left-
aligned). Unlike -print, -printf does not add a newline at the
end of the string. The escapes and directives 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.
\0 ASCII NUL.
\\ A literal backslash (`\').
\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.
%% A literal percent sign.
%a File's last access time in the format returned by the C
ctime(3) function.
%Ak File's last access time in the format specified by k,
which is either `@' or a directive for the C strftime(3)
function. The following shows an incomplete list of pos‐
sible values for k. Please refer to the documentation of
strftime(3) for the full list. Some of the conversion
specification characters might not be available on all
systems, due to differences in the implementation of the
strftime(3) library function.
@ seconds since Jan. 1, 1970, 00:00 GMT, with frac‐
tional part.
Time fields:
H hour (00..23)
I hour (01..12)
k hour ( 0..23)
l hour ( 1..12)
M minute (00..59)
p locale's AM or PM
r time, 12-hour (hh:mm:ss [AP]M)
S Second (00.00 .. 61.00). There is a fractional
part.
T time, 24-hour (hh:mm:ss.xxxxxxxxxx)
+ Date and time, separated by `+', for example
`2004-04-28+22:22:05.0'. This is a GNU extension.
The time is given in the current timezone (which
may be affected by setting the TZ environment
variable). The seconds field includes a frac‐
tional part.
X locale's time representation (H:M:S). The seconds
field includes a fractional part.
Z time zone (e.g., EDT), or nothing if no time zone
is determinable
Date fields:
a locale's abbreviated weekday name (Sun..Sat)
A locale's full weekday name, variable length (Sun‐
day..Saturday)
b locale's abbreviated month name (Jan..Dec)
B locale's full month name, variable length (Janu‐
ary..December)
c locale's date and time (Sat Nov 04 12:02:33 EST
1989). The format is the same as for ctime(3) and
so to preserve compatibility with that format,
there is no fractional part in the seconds field.
d day of month (01..31)
D date (mm/dd/yy)
F date (yyyy-mm-dd)
h same as b
j day of year (001..366)
m month (01..12)
U week number of year with Sunday as first day of
week (00..53)
w day of week (0..6)
W week number of year with Monday as first day of
week (00..53)
x locale's date representation (mm/dd/yy)
y last two digits of year (00..99)
Y year (1970...)
%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.
%Bk File's birth time, i.e., its creation time, in the format
specified by k, which is the same as for %A. This direc‐
tive 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(3) function.
%Ck File's last status change time in the format specified by
k, which is the same as for %A.
%d File's depth in the directory tree; 0 means the file is a
starting-point.
%D The device number on which the file exists (the st_dev
field of struct stat), in decimal.
%f Print the basename; the file's name with any leading di‐
rectories removed (only the last element). For /, the
result is `/'. See the EXAMPLES section for an example.
%F Type of the filesystem the file is on; this value can be
used for -fstype.
%g File's group name, or numeric group ID if the group has
no name.
%G File's numeric group ID.
%h Dirname; the Leading directories of the file's name (all
but the last element). If the file name contains no
slashes (since it is in the current directory) the %h
specifier expands to `.'. For files which are themselves
directories and contain a slash (including /), %h expands
to the empty string. See the EXAMPLES section for an ex‐
ample.
%H Starting-point under which file was found.
%i File's inode number (in decimal).
%k The amount of disk space used for this file in 1 KB
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.
%l Object of symbolic link (empty string if file is not a
symbolic link).
%m File's permission bits (in octal). This option uses the
`traditional' numbers which most Unix implementations
use, but if your particular implementation uses an un‐
usual ordering of octal permissions bits, you will see a
difference between the actual value of the file's mode
and the output of %m. Normally you will want to have a
leading zero on this number, and to do this, you should
use the # flag (as in, for example, `%#m').
%M File's permissions (in symbolic form, as for ls). This
directive is supported in findutils 4.2.5 and later.
%n Number of hard links to file.
%p File's name.
%P File's name with the name of the starting-point under
which it was found removed.
%s File's size in bytes.
%S File's sparseness. This is calculated as (BLOCK‐
SIZE*st_blocks / st_size). The exact value you will get
for an ordinary file of a certain length is system-depen‐
dent. However, normally sparse files will have values
less than 1.0, and files which use indirect blocks may
have a value which is greater than 1.0. In general the
number of blocks used by a file is file system dependent.
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.
%t File's last modification time in the format returned by
the C ctime(3) function.
%Tk File's last modification time in the format specified by
k, which is the same as for %A.
%u File's user name, or numeric user ID if the user has no
name.
%U File's numeric user ID.
%y File's type (like in ls -l), U=unknown type (shouldn't
happen)
%Y File's type (like %y), plus follow symbolic links:
`L'=loop, `N'=nonexistent, `?' for any other error when
determining the type of the target of a symbolic link.
%Z (SELinux only) file's security context.
%{ %[ %(
Reserved for future use.
A `%' character followed by any other character is discarded,
but the other character is printed (don't rely on this, as fur‐
ther format characters may be introduced). 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.
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. The `-' format flag is supported and changes the align‐
ment of a field from right-justified (which is the default) to
left-justified.
See the UNUSUAL FILENAMES section for information about how un‐
usual characters in filenames are handled.
-prune True; if the file is a directory, do not descend into it. If
-depth is given, then -prune has no effect. Because -delete im‐
plies -depth, you cannot usefully use -prune and -delete to‐
gether. For example, to skip the directory src/emacs and all
files and directories under it, and print the names of the other
files found, do something like this:
find . -path ./src/emacs -prune -o -print
-quit Exit immediately (with return value zero if no errors have oc‐
curred). This is different to -prune because -prune only ap‐
plies 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. Af‐
ter -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
OPERATORS
Listed in order of decreasing precedence:
( expr )
Force precedence. Since parentheses are special to the shell,
you will normally need to quote them. Many of the examples in
this manual page use backslashes for this purpose: `\(...\)' in‐
stead of `(...)'.
! expr True if expr is false. This character will also usually need
protection from interpretation by the shell.
-not expr
Same as ! expr, but not POSIX compliant.
expr1 expr2
Two expressions in a row are taken to be joined with an implied
-a; expr2 is not evaluated if expr1 is false.
expr1 -a expr2
Same as expr1 expr2.
expr1 -and expr2
Same as expr1 expr2, but not POSIX compliant.
expr1 -o expr2
Or; expr2 is not evaluated if expr1 is true.
expr1 -or expr2
Same as expr1 -o expr2, but not POSIX compliant.
expr1 , expr2
List; both expr1 and expr2 are always evaluated. The value of
expr1 is discarded; the value of the list is the value of expr2.
The comma operator can be useful for searching for several dif‐
ferent types of thing, but traversing the filesystem hierarchy
only once. The -fprintf action can be used to list the various
matched items into several different output files.
Please note that -a when specified implicitly (for example by two tests
appearing without an explicit operator between them) or explicitly has
higher precedence than -o. This means that find . -name afile -o -name
bfile -print will never print afile.
UNUSUAL FILENAMES
Many of the actions of find result in the printing of data which is un‐
der the control of other users. This includes file names, sizes, modi‐
fication times and so forth. File names are a potential problem since
they can contain any character except `\0' and `/'. Unusual characters
in file names can do unexpected and often undesirable things to your
terminal (for example, changing the settings of your function keys on
some terminals). Unusual characters are handled differently by various
actions, as described below.
-print0, -fprint0
Always print the exact filename, unchanged, even if the output
is going to a terminal.
-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. The
directives %D, %F, %g, %G, %H, %Y, and %y expand to values which
are not under control of files' owners, and so are printed as-
is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t,
%u and %U have values which are under the control of files' own‐
ers but which cannot be used to send arbitrary data to the ter‐
minal, and so these are printed as-is. The directives %f, %h,
%l, %p and %P are 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. The setting of
the LC_CTYPE environment variable is used to determine which
characters need to be quoted.
-print, -fprint
Quoting is handled in the same way as for -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 -ok and -okdir actions print the current filename as-is. This may
change in a future release.
STANDARDS CONFORMANCE
For closest compliance to the POSIX standard, you should set the
POSIXLY_CORRECT environment variable. The following options are speci‐
fied in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition):
-H This option is supported.
-L This option is supported.
-name This option is supported, but POSIX conformance depends on the
POSIX conformance of the system's fnmatch(3) library function.
As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]'
for example) match a leading `.', because IEEE PASC interpreta‐
tion 126 requires this. This is a change from previous versions
of findutils.
-type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and
`s'. GNU find also supports `D', representing a Door, where the
OS provides these. Furthermore, GNU find allows multiple types
to be specified at once in a comma-separated list.
-ok Supported. Interpretation of the response is according to the
`yes' and `no' patterns selected by setting the LC_MESSAGES en‐
vironment variable. When the POSIXLY_CORRECT environment vari‐
able is set, these patterns are taken system's definition of a
positive (yes) or negative (no) response. See the system's doc‐
umentation for nl_langinfo(3), in particular YESEXPR and NOEXPR.
When POSIXLY_CORRECT is not set, the patterns are instead taken
from find's own message catalogue.
-newer Supported. If the file specified is a symbolic link, it is al‐
ways dereferenced. This is a change from previous behaviour,
which used to take the relevant time from the symbolic link; see
the HISTORY section below.
-perm Supported. If the POSIXLY_CORRECT environment variable is not
set, some mode arguments (for example +a+x) which are not valid
in POSIX are supported for backward-compatibility.
Other primaries
The primaries -atime, -ctime, -depth, -exec, -group, -links,
-mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size,
-user and -xdev are all supported.
The POSIX standard specifies parentheses `(', `)', negation `!' and the
logical AND/OR operators -a and -o.
All other options, predicates, expressions and so forth are extensions
beyond the POSIX standard. Many of these extensions are not unique to
GNU find, however.
The POSIX standard requires that find detects loops:
The find utility shall detect infinite loops; that is, entering
a previously visited directory that is an ancestor of the last
file encountered. When it detects an infinite loop, find shall
write a diagnostic message to standard error and shall either
recover its position in the hierarchy or terminate.
GNU find complies with these requirements. The link count of directo‐
ries which contain entries which are hard links to an ancestor will of‐
ten be lower than they otherwise should be. This can mean that GNU
find will sometimes optimise away the visiting of a subdirectory which
is actually a link to an ancestor. Since find does not actually enter
such a subdirectory, it is allowed to avoid emitting a diagnostic mes‐
sage. Although this behaviour may be somewhat confusing, it is un‐
likely that anybody actually depends on this behaviour. If the leaf
optimisation has been turned off with -noleaf, the directory entry will
always be examined and the diagnostic message will be issued where it
is appropriate. Symbolic links cannot be used to create filesystem cy‐
cles as such, but if the -L option or the -follow option is in use, a
diagnostic message is issued when find encounters a loop of symbolic
links. As with loops containing hard links, the leaf optimisation will
often mean that find knows that it doesn't need to call stat() or
chdir() on the symbolic link, so this diagnostic is frequently not nec‐
essary.
The -d option is supported for compatibility with various BSD systems,
but you should use the POSIX-compliant option -depth instead.
The POSIXLY_CORRECT environment variable does not affect the behaviour
of the -regex or -iregex tests because those tests aren't specified in
the POSIX standard.
ENVIRONMENT VARIABLES
LANG Provides a default value for the internationalization variables
that are unset or null.
LC_ALL If set to a non-empty string value, override the values of all
the other internationalization variables.
LC_COLLATE
The POSIX standard specifies that this variable affects the pat‐
tern matching to be used for the -name option. GNU find uses
the fnmatch(3) library function, and so support for LC_COLLATE
depends on the system library. This variable also affects the
interpretation of the response to -ok; while the LC_MESSAGES
variable selects the actual pattern used to interpret the re‐
sponse to -ok, the interpretation of any bracket expressions in
the pattern will be affected by LC_COLLATE.
LC_CTYPE
This variable affects the treatment of character classes used in
regular expressions and also with the -name test, if the sys‐
tem's fnmatch(3) library function supports this. This variable
also affects the interpretation of any character classes in the
regular expressions used to interpret the response to the prompt
issued by -ok. The LC_CTYPE environment variable will also af‐
fect which characters are considered to be unprintable when
filenames are printed; see the section UNUSUAL FILENAMES.
LC_MESSAGES
Determines the locale to be used for internationalised messages.
If the POSIXLY_CORRECT environment variable is set, this also
determines the interpretation of the response to the prompt made
by the -ok action.
NLSPATH
Determines the location of the internationalisation message cat‐
alogues.
PATH Affects the directories which are searched to find the executa‐
bles invoked by -exec, -execdir, -ok and -okdir.
POSIXLY_CORRECT
Determines the block size used by -ls and -fls. If POSIXLY_COR‐
RECT is set, blocks are units of 512 bytes. Otherwise they are
units of 1024 bytes.
Setting this variable also turns off warning messages (that is,
implies -nowarn) by default, because POSIX requires that apart
from the output for -ok, all messages printed on stderr are di‐
agnostics and must result in a non-zero exit status.
When POSIXLY_CORRECT is not set, -perm +zzz is treated just like
-perm /zzz if +zzz is not a valid symbolic mode. When
POSIXLY_CORRECT is set, such constructs are treated as an error.
When POSIXLY_CORRECT is set, the response to the prompt made by
the -ok action is interpreted according to the system's message
catalogue, as opposed to according to find's own message trans‐
lations.
TZ Affects the time zone used for some of the time-related format
directives of -printf and -fprintf.
EXAMPLES
Simple `find|xargs` approach
• Find files named core in or below the directory /tmp and delete
them.
$ find /tmp -name core -type f -print | xargs /bin/rm -f
Note that this will work incorrectly if there are any filenames
containing newlines, single or double quotes, or spaces.
Safer `find -print0 | xargs -0` approach
• Find files named core in or below the directory /tmp and delete
them, processing filenames in such a way that file or directory
names containing single or double quotes, spaces or newlines are
correctly handled.
$ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f
The -name test comes before the -type test in order to avoid
having to call stat(2) on every file.
Note that there is still a race between the time find traverses the hi‐
erarchy printing the matching filenames, and the time the process exe‐
cuted by xargs works with that file.
Processing arbitrary starting points
• 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 exam‐
ined without recursing into directories (in the case one of the
starting points is one).
Executing a command for each file
• Run file on every file in or below the current directory.
$ find . -type f -exec file '{}' \;
Notice that the braces are enclosed in single quote marks to
protect them from interpretation as shell script punctuation.
The semicolon is similarly protected by the use of a backslash,
though single quotes could have been used in that case also.
In many cases, one might prefer the `-exec ... +` or better the `-ex‐
ecdir ... +` syntax for performance and security reasons.
Traversing the filesystem just once - for 2 different actions
• Traverse the filesystem just once, listing set-user-ID files and
directories into /root/suid.txt and large files into
/root/big.txt.
$ find / \
\( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \
\( -size +100M -fprintf /root/big.txt '%-10s %p\n' \)
This example uses the line-continuation character '\' on the
first two lines to instruct the shell to continue reading the
command on the next line.
Searching files by age
• Search for files in your home directory which have been modified
in the last twenty-four hours.
$ find $HOME -mtime 0
This command works this way because the time since each file was
last modified is divided by 24 hours and any remainder is dis‐
carded. That means that to match -mtime 0, a file will have to
have a modification in the past which is less than 24 hours ago.
Searching files by permissions
• Search for files which are executable but not readable.
$ find /sbin /usr/sbin -executable \! -readable -print
• Search for files which have read and write permission for their
owner, and group, but which other users can read but not write
to.
$ find . -perm 664
Files which meet these criteria but have other permissions bits
set (for example if someone can execute the file) will not be
matched.
• Search for files which have read and write permission for their
owner and group, and which other users can read, without regard
to the presence of any extra permission bits (for example the
executable bit).
$ find . -perm -664
This will match a file which has mode 0777, for example.
• Search for files which are writable by somebody (their owner, or
their group, or anybody else).
$ find . -perm /222
• Search for files which are writable by either their owner or
their group.
$ find . -perm /220
$ find . -perm /u+w,g+w
$ find . -perm /u=w,g=w
All three of these commands do the same thing, but the first one
uses the octal representation of the file mode, and the other
two use the symbolic form. The files don't have to be writable
by both the owner and group to be matched; either will do.
• Search for files which are writable by both their owner and
their group.
$ find . -perm -220
$ find . -perm -g+w,u+w
Both these commands do the same thing.
• A more elaborate search on permissions.
$ find . -perm -444 -perm /222 \! -perm /111
$ find . -perm -a+r -perm /a+w \! -perm /a+x
These two commands both search for files that are readable for
everybody (-perm -444 or -perm -a+r), have at least one write
bit set (-perm /222 or -perm /a+w) but are not executable for
anybody (! -perm /111 or ! -perm /a+x respectively).
Pruning - omitting files and subdirectories
• Copy the contents of /source-dir to /dest-dir, but omit files
and directories named .snapshot (and anything in them). It also
omits files or directories whose name ends in `~', but not their
contents.
$ cd /source-dir
$ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \
| cpio -pmd0 /dest-dir
The construct -prune -o \( ... -print0 \) is quite common. The
idea here is that the expression before -prune matches things
which are to be pruned. However, the -prune action itself re‐
turns true, so the following -o ensures that the right hand side
is evaluated only for those directories which didn't get pruned
(the contents of the pruned directories are not even visited, so
their contents are irrelevant). The expression on the right
hand side of the -o is in parentheses only for clarity. It em‐
phasises that the -print0 action takes place only for things
that didn't have -prune applied to them. Because the default
`and' condition between tests binds more tightly than -o, this
is the default anyway, but the parentheses help to show what is
going on.
• Given the following directory of projects and their associated
SCM administrative directories, perform an efficient search for
the projects' roots:
$ find repo/ \
\( -exec test -d '{}/.svn' \; \
-or -exec test -d '{}/.git' \; \
-or -exec test -d '{}/CVS' \; \
\) -print -prune
Sample output:
repo/project1/CVS
repo/gnu/project2/.svn
repo/gnu/project3/.svn
repo/gnu/project3/src/.svn
repo/project4/.git
In this example, -prune prevents unnecessary descent into direc‐
tories that have already been discovered (for example we do not
search project3/src because we already found project3/.svn), but
ensures sibling directories (project2 and project3) are found.
Other useful examples
• Search for several file types.
$ find /tmp -type f,d,l
Search for files, directories, and symbolic links in the direc‐
tory /tmp passing these types as a comma-separated list (GNU ex‐
tension), which is otherwise equivalent to the longer, yet more
portable:
$ find /tmp \( -type f -o -type d -o -type l \)
• Search for files with the particular name needle and stop imme‐
diately when we find the first one.
$ find / -name needle -print -quit
• Demonstrate the interpretation of the %f and %h format direc‐
tives of the -printf action for some corner-cases. Here is an
example including some output.
$ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n'
[.][.]
[.][..]
[][/]
[][tmp]
[/tmp][TRACE]
[.][compile]
[compile/64/tests][find]
EXIT STATUS
find exits with status 0 if all files are processed successfully,
greater than 0 if errors occur. This is deliberately a very broad de‐
scription, but if the return value is non-zero, you should not rely on
the correctness of the results of find.
When some error occurs, find may stop immediately, without completing
all the actions specified. For example, some starting points may not
have been examined or some pending program invocations for
-exec ... {} + or -execdir ... {} + may not have been performed.
HISTORY
As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for exam‐
ple) used in filename patterns match a leading `.', because IEEE POSIX
interpretation 126 requires this.
As of findutils-4.3.3, -perm /000 now matches all files instead of
none.
Nanosecond-resolution timestamps were implemented in findutils-4.3.3.
As of findutils-4.3.11, the -delete action sets find's exit status to a
nonzero value when it fails. However, find will not exit immediately.
Previously, find's exit status was unaffected by the failure of
-delete.
Feature Added in Also occurs in
-files0-from 4.9.0
-newerXY 4.3.3 BSD
-D 4.3.1
-O 4.3.1
-readable 4.3.0
-writable 4.3.0
-executable 4.3.0
-regextype 4.2.24
-exec ... + 4.2.12 POSIX
-execdir 4.2.12 BSD
-okdir 4.2.12
-samefile 4.2.11
-H 4.2.5 POSIX
-L 4.2.5 POSIX
-P 4.2.5 BSD
-delete 4.2.3
-quit 4.2.3
-d 4.2.3 BSD
-wholename 4.2.0
-iwholename 4.2.0
-ignore_readdir_race 4.2.0
-fls 4.0
-ilname 3.8
-iname 3.8
-ipath 3.8
-iregex 3.8
The syntax -perm +MODE was removed in findutils-4.5.12, in favour of
-perm /MODE. The +MODE syntax had been deprecated since findu‐
tils-4.2.21 which was released in 2005.
NON-BUGS
Operator precedence surprises
The command find . -name afile -o -name bfile -print will never print
afile because this is actually equivalent to find . -name afile -o \(
-name bfile -a -print \). Remember that the precedence of -a is higher
than that of -o and when there is no operator specified between tests,
-a is assumed.
“paths must precede expression” error message
$ find . -name *.c -print
find: paths must precede expression
find: possible unquoted pattern after predicate `-name'?
This happens when the shell could expand the pattern *.c to more than
one file name existing in the current directory, and passing the re‐
sulting file names in the command line to find like this:
find . -name frcode.c locate.c word_io.c -print
That command is of course not going to work, because the -name predi‐
cate allows exactly only one pattern as argument. Instead of doing
things this way, you should enclose the pattern in quotes or escape the
wildcard, thus allowing find to use the pattern with the wildcard dur‐
ing the search for file name matching instead of file names expanded by
the parent shell:
$ find . -name '*.c' -print
$ find . -name \*.c -print
BUGS
There are security problems inherent in the behaviour that the POSIX
standard specifies for find, which therefore cannot be fixed. For ex‐
ample, the -exec action is inherently insecure, and -execdir should be
used instead.
The environment variable LC_COLLATE has no effect on the -ok action.
REPORTING BUGS
GNU findutils online help: <https://www.gnu.org/software/findu‐
tils/#get-help>
Report any translation bugs to <https://translationproject.org/team/>
Report any other issue via the form at the GNU Savannah bug tracker:
<https://savannah.gnu.org/bugs/?group=findutils>
General topics about the GNU findutils package are discussed at the
bug-findutils mailing list:
<https://lists.gnu.org/mailman/listinfo/bug-findutils>
COPYRIGHT
Copyright © 1990-2022 Free Software Foundation, Inc. License GPLv3+:
GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
SEE ALSO
chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2),
ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7)
Full documentation <https://www.gnu.org/software/findutils/find>
or available locally via: info find
FIND(1)
man find 번역기 번역본
FIND(1) 일반 명령 설명서 FIND(1)
이름
find - 디렉토리 계층에서 파일 검색
요약
find [-H] [-L] [-P] [-D debugopts] [-Olevel] [시작점...] [ex‐
표현식]
설명
이 매뉴얼 페이지는 find의 GNU 버전을 설명합니다. GNU find는 주어진 시작점에서 루트된 디렉토리 트리를 검색합니다. 주어진 표현식을 왼쪽에서 오른쪽으로 평가하여 우선순위 규칙(연산자 섹션 참조)에 따라 검색합니다. 결과가 알려질 때까지(왼쪽은 and 연산의 경우 거짓이고 or 연산의 경우 참임) find는 다음 파일 이름으로 이동합니다. 시작점이 지정되지 않으면 `.'이 가정됩니다.
보안이 중요한 환경에서 find를 사용하는 경우(예: 다른 사용자가 쓸 수 있는 디렉토리를 검색하는 데 사용하는 경우) findutils 설명서의 `보안 고려 사항' 장을 읽어야 합니다. 이 장은 파일 찾기라고 하며 findutils와 함께 제공됩니다. 해당 문서에는 이 매뉴얼 페이지보다 훨씬 더 자세한 내용과 논의가 포함되어 있으므로 더 유용한 정보 출처가 될 수 있습니다.
옵션
-H, -L 및 -P 옵션은 심볼릭 링크의 처리를 제어합니다.
다음에 오는 명령줄 인수는 `-'로 시작하는 첫 번째 인수 또는 `(' 또는 `!' 인수까지 검사할 파일 또는 디렉토리의 이름으로 간주됩니다. 해당 인수와 그 뒤의 모든 인수는 검색할 내용을 설명하는 표현식으로 간주됩니다. 경로가 지정되지 않으면 현재 디렉토리가 사용됩니다. 표현식이 지정되지 않으면 표현식 -print가 사용됩니다(하지만
대신 -print0을 사용하는 것이 좋습니다).
이 매뉴얼 페이지에서는 표현식 목록 내의 `옵션'에 대해 설명합니다.
이러한 옵션은 find의 동작을 제어하지만 마지막 경로 이름 바로 뒤에 지정됩니다. 다섯 가지 `실제' 옵션인 -H, -L, -P, -D 및 -O는 첫 번째 경로 이름 앞에 나타나야 합니다(있는 경우). 이중
대시 --는 이론적으로 나머지 인수가 옵션이 아님을 알리는 데 사용될 수 있지만 find가 다음 경로 인수의 끝을 결정하는 방식 때문에 실제로는 작동하지 않습니다. 표현식 인수가 올 때까지 읽습니다(또한 `-'로 시작합니다. 이제 경로 인수가 `-'로 시작하면 find는 이를 대신 표현식 인수로 처리합니다. 따라서 모든 시작점이 그렇게 취급되도록 하고 특히 호출 셸에서 확장한 와일드카드 패턴이 실수로 표현식 인수로 취급되지 않도록 하려면 일반적으로 와일드카드나 의심스러운 경로 이름 앞에 `./'를 접두사로 붙이거나 '/'로 시작하는 절대 경로 이름을 사용하는 것이 더 안전합니다. 또는 일반적으로 이식성이 없지만 GNU 옵션 -files0-from을 사용하여 임의의 시작점을 find에 전달하는 것이 안전합니다.
-P 심볼릭 링크를 따르지 않습니다. 이는 기본 동작입니다.
find가 파일에 대한 정보를 검사하거나 인쇄하고 파일이 심볼릭 링크인 경우 사용된 정보는 심볼릭 링크 자체의 속성에서 가져옵니다.
-L 심볼릭 링크를 따릅니다. find가 파일에 대한 정보를 조사하거나 인쇄할 때 사용되는 정보는 링크 자체가 아닌 링크가 가리키는 파일의 속성에서 가져와야 합니다(손상된 심볼릭 링크이거나 find가 링크가 가리키는 파일을 조사할 수 없는 경우 제외). 이 옵션을 사용하면 -noleaf가 적용됩니다. 나중에 -P 옵션을 사용하면 -noleaf가 여전히 적용됩니다. -L이 적용되고 find가 검색 중에 하위 디렉토리로 가는 심볼릭 링크를 발견하면 심볼릭 링크가 가리키는 하위 디렉토리가 검색됩니다.
-L 옵션이 적용되면 -type 술어는 항상 링크 자체가 아니라 심볼릭 링크가 가리키는 파일의 유형과 일치합니다(심볼릭 링크가 끊어진 경우 제외). find가 실행되는 동안 심볼릭 링크가 끊어질 수 있는 동작(예: -delete)은 혼란스러운 동작을 일으킬 수 있습니다. -L을 사용하면 -lname 및 -ilname 술어가 항상 false를 반환합니다.
-H 명령줄 인수를 처리하는 경우를 제외하고 심볼릭 링크를 따르지 않습니다. find가 파일에 대한 정보를 조사하거나 인쇄할 때 사용된 정보는 심볼릭 링크 자체의 속성에서 가져옵니다. 이 동작에 대한 유일한 예외는 명령줄에 지정된 파일이 심볼릭 링크이고 링크를 확인할 수 있는 경우입니다. 이 상황에서는 사용된 정보는 링크가 가리키는 것에서 가져옵니다(즉, 링크를 따릅니다). 심볼릭 링크가 가리키는 파일을 조사할 수 없는 경우 링크 자체에 대한 정보가 폴백으로 사용됩니다. -H가 적용되고 명령줄에 지정된 경로 중 하나가 디렉토리에 대한 심볼릭 링크인 경우 해당 디렉토리의 내용이 조사됩니다(물론 -maxdepth 0은 이를 방지합니다).
-H, -L 및 -P 중 두 개 이상을 지정한 경우 각각이 다른 것을 재정의합니다. 명령줄에 나타나는 마지막 것이 적용됩니다. 기본값이므로 -H 또는 -L이 지정되지 않은 경우 -P 옵션이 유효한 것으로 간주해야 합니다.
GNU find는 검색이 시작되기 전에 명령줄 자체를 처리하는 동안 자주 파일을 통계합니다. 이러한 옵션은 해당 인수가 처리되는 방식에도 영향을 미칩니다. 구체적으로, 명령줄에 나열된 파일을 현재 고려 중인 파일과 비교하는 여러 가지 테스트가 있습니다. 각 경우 명령줄에 지정된 파일이 검사되고 일부 속성이 저장됩니다. 명명된 파일이 실제로 심볼릭 링크이고 -P 옵션이 적용되거나 -H나 -L이 지정되지 않은 경우 비교에 사용되는 정보는 심볼릭 링크의 속성에서 가져옵니다. 그렇지 않으면 링크가 가리키는 파일의 속성에서 가져옵니다. find가 링크를 따를 수 없는 경우(예: 권한이 충분하지 않거나 링크가 존재하지 않는 파일을 가리키는 경우) 링크 자체의 속성이 사용됩니다.
-H 또는 -L 옵션이 적용되는 경우 -newer의 인수로 나열된 모든 심볼릭 링크는 역참조되고 타임스탬프는 심볼릭 링크가 가리키는 파일에서 가져옵니다. 동일한 고려 사항이 -newerXY, -anewer 및 -cnewer에도 적용됩니다.
-follow 옵션은 -L과 비슷한 효과가 있지만, 나타나는 지점에서 적용됩니다(즉, -L이 사용되지 않고 -follow가 사용되는 경우 명령줄에서 -follow 뒤에 나타나는 모든 심볼릭 링크는 역참조되고 그 앞에 나타나는 심볼릭 링크는 역참조되지 않습니다).
-D debugopts
진단 정보를 인쇄합니다. 이는 find가 원하는 작업을 수행하지 않는 이유를 진단하는 데 도움이 될 수 있습니다.
디버그 옵션 목록은 쉼표로 구분해야 합니다.
디버그 옵션의 호환성은 findutils 릴리스 간에 보장되지 않습니다.
유효한 디버그 옵션의 전체 목록은
find -D help의 출력을 참조하세요. 유효한 디버그 옵션에는 다음이 포함됩니다.
exec -exec, -execdir,
-ok 및 -okdir과 관련된 진단 정보를 표시합니다.
opt 표현식 트리의 최적화와 관련된 진단 정보를 인쇄합니다. -O 옵션을 참조하세요.
rates 각 술어가 성공하거나 실패한 빈도를 나타내는 요약을 인쇄합니다.
search 디렉터리 트리를 자세히 탐색합니다.
stat stat 및
lstat 시스템 호출로 파일을 검사할 때 메시지를 인쇄합니다. find 프로그램은 이러한 호출을 최소화하려고 합니다.
tree 표현식 트리를 원래 및 최적화된
형태로 표시합니다.
all 다른 모든 디버그 옵션을 활성화합니다(도움말 제외).
help 디버깅 옵션을 설명합니다.
-Olevel
쿼리 최적화를 활성화합니다. find 프로그램은 테스트를 재정렬하여 전반적인 효과를 유지하면서 실행 속도를 높입니다. 즉, 부작용이 있는 술어는 서로에 대해 재정렬되지 않습니다. 각 최적화 수준에서 수행되는 최적화는 다음과 같습니다.
0 최적화 수준 1과 동일합니다.
1 이는 기본 최적화 수준이며 기존 동작에 해당합니다. 표현식이 재정렬되어 파일 이름(예: -name 및 -regex)에만 기반한 테스트가 먼저 수행됩니다.
2 모든 -type 또는 -xtype 테스트는 파일 이름에만 기반한 테스트 후에 수행되지만 inode의 정보가 필요한 테스트는 전에 수행됩니다. 많은 최신 버전의 Unix에서 파일 유형은 readdir()에서 반환되므로 이러한 술어는 파일을 먼저 stat해야 하는 술어보다 평가하는 것이 빠릅니다. -fstype FOO 술어를 사용하고 find가 시작될 때 알려지지 않은(즉, `/etc/mtab'에 있는) 파일 시스템 유형 FOO를 지정하는 경우 해당 술어는 -false와 동일합니다.
3 이 최적화 수준에서 전체 비용 기반 쿼리 최적화기가 활성화됩니다. 테스트 순서가 수정되어
저렴한(즉, 빠른) 테스트가 먼저 수행되고 필요한 경우 더 비싼 테스트가 나중에 수행됩니다.
각 비용 대역 내에서 술어는 성공할 가능성이 있는지 여부에 따라 더 일찍 또는 더 늦게 평가됩니다.
-o의 경우 성공할 가능성이 있는 술어가 더 일찍 평가되고 -a의 경우 실패할 가능성이 있는 술어가 더 일찍 평가됩니다.
비용 기반 최적화기는 주어진 테스트가 성공할 가능성에 대한 고정 관념을 가지고 있습니다. 어떤 경우에는 확률이 테스트의 특정 특성을 고려합니다(예: -type f는 -type c보다 성공할 가능성이 더 높다고 가정).
비용 기반 최적화기가 현재 평가 중입니다. 실제로 find의 성능을 개선하지 못하면 다시 제거됩니다.
반대로 신뢰할 수 있고 견고하며 효과적인 것으로 입증된 최적화는 시간이 지남에 따라 더 낮은 최적화 수준에서 활성화될 수 있습니다.
그러나 기본 동작(즉, 최적화 수준 1)은 4.3.x 릴리스 시리즈에서 변경되지 않습니다.
findutils 테스트 모음은 각 최적화 수준에서 find의 모든 테스트를 실행하고 결과가 동일한지 확인합니다.
표현식
시작점 목록 뒤에 있는 명령줄의 일부는
표현식입니다. 이것은 파일을 어떻게 매치하고 매치된 파일로 무엇을 하는지 설명하는 일종의 쿼리 사양입니다. 표현식은 일련의 것들로 구성됩니다.
테스트 테스트는 일반적으로 고려 중인 파일의 일부 속성에 따라 참 또는 거짓 값을 반환합니다. 예를 들어 -empty 테스트는 현재 파일이 비어 있을 때만 참입니다.
동작
동작에는 부작용(예: 표준 출력에 무언가를 인쇄하는 것)이 있으며 일반적으로 성공 여부에 따라 참 또는 거짓을 반환합니다. 예를 들어 -print 동작은
표준 출력에 현재 파일의 이름을 인쇄합니다.
전역 옵션
전역 옵션은 명령줄의 모든 부분에 지정된 테스트 및 동작의 작동에 영향을 미칩니다. 전역 옵션은 항상 참을 반환합니다. 예를 들어 -depth 옵션은 find가 깊이 우선 순서로 파일 시스템을 탐색하도록 합니다.
위치 옵션
위치 옵션은 다음에 오는 테스트 또는 작업에만 영향을 미칩니다. 위치 옵션은 항상 true를 반환합니다. 예를 들어 -regextype
옵션은 위치적이며 명령줄에서 나중에 나타나는 정규 표현식에 대한 정규 표현식 방언을 지정합니다.
연산자
연산자는 표현식 내의 다른 항목을 결합합니다.
예를 들어 -o(논리적 OR을 의미) 및 -a(논리적 AND를 의미)가 있습니다. 연산자가 없는 경우 -a가 가정됩니다.
-print 작업은 -prune 또는 -quit 이외의 작업을 포함하지 않는 한 전체 표현식이 true인 모든 파일에서 수행됩니다.
기본 -print를 억제하는 작업은 -delete, -exec, -execdir,
-ok, -okdir, -fls, -fprint, -fprintf, -ls, -print 및 -printf입니다.
-delete 작업은 옵션처럼 작동합니다(-depth를 의미하기 때문).
위치 옵션
위치 옵션은 항상 true를 반환합니다. 이 옵션은 명령줄에서 나중에 발생하는 테스트에만 영향을 미칩니다.
-daystart
24시간 전이 아닌 오늘부터의 시간(-amin, -atime, -cmin, -ctime, -mmin 및 -mtime)을 측정합니다. 이 옵션은 명령줄에서 나중에 나타나는 테스트에만 영향을 미칩니다.
-follow
더 이상 사용되지 않습니다. 대신 -L 옵션을 사용하세요. 심볼릭
링크 참조 해제. -noleaf를 의미합니다. -follow 옵션은 명령줄에서 뒤에 나타나는 테스트에만 영향을 미칩니다. -H
또는 -L 옵션이 지정되지 않은 경우 -follow 옵션의 위치는 -newer 술어의 동작을 변경합니다. -newer의 인수로 나열된 모든 파일은 심볼릭 링크인 경우 참조 해제됩니다. -newerXY, -anewer 및 -cnewer에도 동일한 고려 사항이 적용됩니다. 마찬가지로 -type 술어는 항상
링크 자체가 아니라 심볼릭 링크가 가리키는 파일의 유형과 일치합니다. -follow를 사용하면 -lname
및 -ilname 술어가 항상 false를 반환합니다.
-regextype type
-regex 및 -iregex 테스트에서 이해하는 정규 표현식 구문을 변경합니다. 이는 나중에 명령줄에서 발생합니다.
알려진 정규 표현식 유형을 보려면 -regextype 도움말을 사용하세요.
Texinfo 설명서(참조)는 다양한 유형의 정규 표현식의 의미와 차이점을 설명합니다.
-warn, -nowarn
경고 메시지를 켜거나 끕니다. 이러한 경고는 명령줄 사용에만 적용되며 find가 디렉토리를 검색할 때 발생할 수 있는 조건에는 적용되지 않습니다. 기본 동작은
표준 입력이 tty인 경우 -warn에 해당하고 그렇지 않은 경우 -nowarn에 해당합니다. 명령줄 사용과 관련된 경고 메시지가 생성되면 find의 종료 상태에는 영향을 미치지 않습니다. POSIXLY_CORRECT 환경 변수가 설정되고 -warn도
사용되는 경우, 어떤 경고가 활성화될지 지정되지 않습니다.
전역 옵션
전역 옵션은 항상 true를 반환합니다. 전역 옵션은 명령줄에서 더 일찍 발생하는 테스트에도 적용됩니다. 혼동을 방지하기 위해
전역 옵션은 명령줄에서 시작점 목록 뒤, 첫 번째 테스트, 위치 옵션 또는 작업 바로 앞에 지정해야 합니다.
다른 곳에서 전역 옵션을 지정하는 경우 find는 혼동을 줄 수 있다는 경고 메시지를 표시합니다.
전역 옵션은 시작점 목록 뒤에 발생하므로 -L과 같은 종류의 옵션이 아닙니다.
-d FreeBSD, NetBSD, MacOS X 및 OpenBSD와의 호환성을 위해 -depth의 동의어입니다.
-depth 디렉토리 자체보다 먼저 각 디렉토리의 내용을 처리합니다.
-delete 작업도 -depth를 의미합니다.
-files0-from file
명령줄에서 시작점을 가져오는 대신 파일에서 시작점을 읽습니다. 명령줄에서 인수를 통해 시작점을 전달하는 것의 알려진 제한 사항, 즉 파일 이름의 양 제한 및 파일 이름이 옵션 이름과 충돌하는 본질적인 모호성과 달리 이 옵션을 사용하면 임의의 수의 시작점을 안전하게 전달할 수 있습니다.
이 옵션을 사용하고 명령줄에서 시작점을 전달하는 것은 상호 배타적이므로 동시에 허용되지 않습니다.
file 인수는 필수입니다. -files0-from -을 사용하여 표준 입력 스트림에서 시작점 목록을 읽을 수 있습니다.
예를 들어 파이프에서 읽을 수 있습니다. 이 경우 -ok 및 -okdir 작업은 허용되지 않습니다. 이는 사용자 확인을 받기 위해 표준 입력에서 읽는 것을 방해하기 때문입니다.
file의 시작점은 ASCII NUL
문자로 구분해야 합니다. 연속된 두 개의 NUL 문자, 즉 0 길이의 파일 이름을 가진 시작점은 허용되지 않으며, 오류 진단과 나중에 0이 아닌 종료 코드가 뒤따릅니다.
주어진 파일이 비어 있는 경우 find는 시작점을 처리하지 않으므로 프로그램 인수를 구문 분석한 후 즉시 종료됩니다. 이는 경로 인수가 전달되지 않으면 find가 현재 디렉토리를 시작점으로 가정하는 표준 호출과는 다릅니다.
시작점의 처리가 평소와 같습니다.
예를 들어 find는 달리 방지되지 않는 한 하위 디렉토리로 재귀적으로 이동합니다.
시작점만 처리하려면 -maxdepth 0을 추가로 전달할 수 있습니다.
추가 참고 사항: 입력 파일에 파일이 두 번 이상 나열된 경우 두 번 이상 방문했는지 여부는 지정되지 않습니다.
find 작업 중에 파일이 변형된 경우 결과도 지정되지 않습니다. 마지막으로, find가 종료될 때
명명된 파일 내의 seek 위치는 -quit 또는 다른 방식으로든 지정되지 않습니다. 여기서 "지정되지 않음"이란
작동하거나 특정한 일을 할 수도 있고 하지 않을 수도 있으며,
동작은 플랫폼마다 또는 find-utils 릴리스마다 변경될 수 있음을 의미합니다.
-help, --help
find의 명령줄 사용법을 요약해서 출력하고 종료합니다.
-ignore_readdir_race
일반적으로 find는 파일을 stat하지 못하면 오류 메시지를 내보냅니다. 이 옵션을 제공하고 find가 디렉토리에서 파일 이름을 읽는 시간과 파일을 stat하려고 하는 시간 사이에 파일이 삭제되면 오류 메시지가 발생하지 않습니다. 이는 명령줄에 이름이 지정된 파일이나 디렉토리에도 적용됩니다. 이 옵션은 명령줄을 읽는 시점에 적용되므로 이 옵션을 켜고 파일 시스템의 일부를 검색할 수 없고 이 옵션을 끄고 파일 시스템의 일부를 검색할 수 없습니다(이 작업을 수행해야 하는 경우 두 개의 find 명령을 실행해야 합니다. 하나는 옵션을 사용하고 다른 하나는 옵션을 사용하지 않고 실행해야 합니다.)
또한 -ignore_readdir_race 옵션과 함께 find를 실행하면 부모 디렉토리를 읽은 후 파일이 사라진 경우 -delete 작업의 오류를 무시합니다. 오류 진단을 출력하지 않으며 -delete 작업의 반환 코드는 참이 됩니다.
-maxdepth levels
시작점 아래의 디렉토리의 최대 수준(음이 아닌 정수)에서 아래로 내립니다. -maxdepth 0을 사용하면 시작점 자체에만 테스트와 작업을 적용합니다.
-mindepth levels
수준(음이 아닌 정수)보다 낮은 수준에서는 테스트나 작업을 적용하지 않습니다. -mindepth 1을 사용하면 시작점을 제외한 모든 파일을 처리합니다.
-mount 다른 파일 시스템의 디렉토리를 아래로 내립니다. 다른 버전의 find와 호환되도록 -xdev의 대체 이름입니다.
-noignore_readdir_race
-ignore_readdir_race의 효과를 끕니다.
-noleaf
디렉토리에 하드 링크 수보다 2개 적은 하위 디렉토리가 있다고 가정하여 최적화하지 마십시오. 이 옵션은 CD-ROM이나 MS-DOS 파일 시스템 또는 AFS 볼륨 마운트 지점과 같이 Unix 디렉토리 링크 규칙을 따르지 않는 파일 시스템을 검색할 때 필요합니다. 일반 Unix 파일 시스템의 각 디렉토리에는 이름과 `.' 항목이라는 최소 2개의 하드 링크가 있습니다. 또한 하위 디렉토리(있는 경우)에는 해당 디렉토리에 연결된 `..' 항목이 있습니다. find가 디렉토리를 검사할 때 디렉토리의 링크 수보다 2개 적은 하위 디렉토리를 stat한 후에는 디렉토리의 나머지 항목이 디렉토리가 아닌 것(디렉토리 트리의 `leaf' 파일)임을 알고 있습니다. 파일 이름만 검사하면 되는 경우 stat할 필요가 없습니다. 이렇게 하면 검색 속도가 상당히 빨라집니다.
-version, --version
find 버전 번호를 인쇄하고 종료합니다.
-xdev 다른 파일 시스템의 디렉토리로 내려가지 않습니다.
테스트
-newerXY 및 -samefile과 같은 일부 테스트는 현재 검사 중인 파일과 명령줄에 지정된 참조 파일을 비교할 수 있도록 합니다. 이러한 테스트를 사용하는 경우 참조 파일의 해석은 옵션 -H, -L 및 -P와 이전의 -follow에 따라 결정되지만 참조 파일은 명령줄이 구문 분석될 때 한 번만 검사됩니다. 참조 파일을 검사할 수 없는 경우(예: stat(2) 시스템 호출이 실패하는 경우) 오류 메시지가 발행되고 find는 0이 아닌 상태로 종료됩니다.
숫자 인수 n은 테스트(예: -amin, -mtime,
-gid, -inum, -links, -size, -uid 및 -used)에 다음과 같이 지정할 수 있습니다.
+n(n보다 큰 경우),
-n(n보다 작은 경우),
n(정확히 n인 경우)
지원되는 테스트:
-amin n
파일이 마지막으로 액세스된 시간은 n분 전, 그 이상 또는 정확히 n분 전입니다.
-anewer reference
현재 파일의 마지막 액세스 시간이 참조 파일의 마지막 데이터 수정 시간보다 최근입니다.
reference가 심볼릭 링크이고 -H 옵션 또는 -L 옵션이 적용되면
해당 파일의 마지막 데이터 수정 시간이 항상 사용됩니다.
-atime n
파일이 마지막으로 액세스된 시간은 n*24시간 전, 그 이상 또는 정확히 n시간 전입니다. find가 파일이 마지막으로 액세스된 24시간 기간을 몇 번인지 알아낼 때 소수 부분은 무시되므로 -atime +1과 일치하려면 파일이 최소 2일 전에 액세스되어야 합니다.
-cmin n
파일의 상태가 마지막으로 변경된 시간은 n분 전, 그 이상 또는 정확히 n분 전입니다.
-cnewer reference
현재 파일의 마지막 상태 변경 시간이 참조 파일의 마지막 데이터 수정 시간보다 최근입니다. reference가 심볼릭 링크이고 -H 옵션 또는 -L 옵션이 적용된 경우 해당 파일의 마지막 데이터 수정 시간이 항상 사용됩니다.
-ctime n
파일의 상태가 마지막으로 변경된 시간보다 짧거나 길거나 정확히
n*24시간 전입니다. -atime에 대한 주석을 참조하여 반올림이 파일 상태 변경 시간 해석에 어떤 영향을 미치는지 이해하세요.
-empty 파일이 비어 있고 일반 파일이거나 디렉토리입니다.
-executable
실행 파일과 현재 사용자가 검색할 수 있는(파일 이름 확인 관점에서) 디렉토리와 일치합니다. 여기에는 액세스 제어 목록과 -perm 테스트에서 무시하는 기타 권한 아티팩트가 고려됩니다. 이 테스트는 access(2) 시스템 호출을 사용하므로 UID 매핑(또는 루트 스쿼싱)을 수행하는 NFS 서버에 속을 수 있습니다. 많은 시스템이 클라이언트 커널에서 access(2)를 구현하여 서버에 보관된 UID 매핑 정보를 사용할 수 없기 때문입니다. 이 테스트는 access(2) 시스템 호출의 결과에만 기반하기 때문에 이 테스트가 성공한 파일이 실제로 실행될 수 있다는 보장은 없습니다.
-false 항상 거짓입니다.
-fstype type
파일은 type 유형의 파일 시스템에 있습니다. 유효한 파일 시스템 유형은 Unix의 버전마다 다릅니다. Unix의 일부 버전에서 허용되는 파일 시스템 유형의 불완전한 목록은 다음과 같습니다. ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. %F 지시문과 함께 -printf를 사용하여 파일 시스템의 유형을 확인할 수 있습니다.
-gid n 파일의 숫자 그룹 ID가 n보다 작거나, 크거나, 정확히 n입니다.
-group gname
파일이 그룹 gname에 속합니다(숫자 그룹 ID 허용).
-ilname pattern
-lname과 비슷하지만, 일치 항목은 대소문자를 구분하지 않습니다. -L 옵션 또는 -follow 옵션이 적용되면 이 테스트는 심볼릭 링크가 끊어지지 않는 한 false를 반환합니다.
-iname pattern
-name과 비슷하지만, 일치 항목은 대소문자를 구분하지 않습니다. 예를 들어,
패턴 `fo*'와 `F??'는 파일 이름 `Foo', `FOO',
`foo', `fOo' 등과 일치합니다. 패턴 `*foo*`는 '.foobar'라는 파일과도 일치합니다.
-inum n
파일의 inode 번호가 n보다 작거나 크거나 정확히 n입니다.
일반적으로 -samefile 테스트를 대신 사용하는 것이 더 쉽습니다.
-ipath 패턴
-path와 유사하지만 일치 항목은 대소문자를 구분하지 않습니다.
-iregex 패턴
-regex와 유사하지만 일치 항목은 대소문자를 구분하지 않습니다.
-iwholename 패턴
-ipath를 참조하세요. 이 대안은 -ipath보다 이식성이 떨어집니다.
-links n
파일의 하드 링크가 n보다 작거나 크거나 정확히 n입니다.
-lname 패턴
파일이 내용이 셸 패턴 패턴과 일치하는 심볼릭 링크입니다. 메타 문자는 `/' 또는 `.'을 특별히 처리하지 않습니다. -L 옵션 또는 -follow 옵션이 적용되면 심볼릭 링크가 끊어지지 않는 한 이 테스트는 false를 반환합니다.
-mmin n
파일의 데이터가 마지막으로 수정된 시간은 n분 전, 그보다 크거나 정확히 n분 전입니다.
-mtime n
파일의 데이터가 마지막으로 수정된 시간은
n*24시간 전보다 짧거나 길거나 정확히
n*24시간 전입니다. -atime에 대한 주석을 참조하여
반올림이 파일 수정 시간 해석에 어떤 영향을 미치는지 이해하세요.
-name pattern
파일 이름의 기본(선행 디렉터리가 제거된 경로)은 셸 패턴 pattern과 일치합니다. 선행 디렉터리가 제거되었으므로 -name과 일치하는 것으로 간주되는 파일 이름에는
슬래시가 포함되지 않으므로 `-name a/b'는
어떤 것과도 일치하지 않습니다(대신 -path를 사용해야 할 수도 있음). 환경 변수 POSIXLY_CORRECT가 설정되어 있지 않으면
이를 시도하면 경고가 발생합니다. 메타문자(`*', `?',
및 `[]')는 기본 이름의 시작 부분에 있는 `.'과 일치합니다(이는
findutils-4.2.2의 변경 사항입니다. 아래 STANDARDS CONFORMANCE 섹션 참조). 디렉터리와 그 아래의 파일을 무시하려면 트리의 모든 파일을 확인하는 대신 -prune
을 사용합니다. 예를
해당 작업의 설명에서 확인하세요. 중괄호는
특별한 것으로 인식되지 않습니다. Bash를 포함한 일부 셸이
셸 패턴에서 중괄호에 특별한 의미를 부여한다는 사실에도 불구하고요.
파일 이름 일치는 fnmatch(3)
라이브러리 함수를 사용하여 수행됩니다. 셸에서 패턴을 확장하지 못하도록 패턴을 따옴표로 묶는 것을 잊지 마세요.
-newer reference
현재 파일의 마지막 데이터 수정 시간이
참조 파일의 마지막 데이터 수정 시간보다 최근입니다.
reference가 심볼릭 링크이고 -H 옵션 또는
-L 옵션이 적용되면 해당 링크가 가리키는 파일의 마지막 데이터 수정 시간이 항상 사용됩니다.
-newerXY reference
고려 중인 파일의 타임스탬프 X가 파일 참조의 타임스탬프 Y보다 최신이면 성공합니다. X와 Y 문자는 다음 문자 중 하나일 수 있습니다.
a 파일 참조의 액세스 시간
B 파일 참조의 생성 시간
c 참조의 inode 상태 변경 시간
m 파일 참조의 수정 시간
t 참조는 시간으로 직접 해석됩니다.
일부 조합은 유효하지 않습니다. 예를 들어 X가 t가 되는 것은 유효하지 않습니다. 일부 조합은 모든 시스템에서 구현되지 않습니다.
예를 들어 B는 모든 시스템에서 지원되지 않습니다. 유효하지 않거나
지원되지 않는 XY 조합을 지정하면 치명적인 오류가 발생합니다. 시간 지정은 GNU date의 -d 옵션에 대한 인수와 동일하게 해석됩니다. 참조 파일의 생성 시간을 사용하려고 하고 생성 시간을 확인할 수 없는 경우 치명적인 오류 메시지가 발생합니다. 검사 중인 파일의 생성 시간을 참조하는 테스트를 지정하면 생성 시간을 알 수 없는 모든 파일에 대해 이 테스트가 실패합니다.
-nogroup
파일의 숫자 그룹 ID에 해당하는 그룹이 없습니다.
-nouser
파일의 숫자 사용자 ID에 해당하는 사용자가 없습니다.
-path pattern
파일 이름이 셸 패턴 pattern과 일치합니다. 메타 문자는 `/' 또는 `.'를 특별히 취급하지 않습니다. 예를 들어
find . -path "./sr*sc"는 ./src/misc라는 디렉토리에 대한 항목을 인쇄합니다(있는 경우). 전체 디렉토리 트리를 무시하려면 트리의 모든 파일을 확인하는 대신 -prune을 사용합니다. 패턴
일치 테스트는 명령줄에 지정된 시작점 중 하나에서 시작하여 전체 파일 이름에 적용됩니다. 관련 시작점도 절대 경로인 경우에만
절대 경로 이름을 사용하는 것이 합리적입니다. 즉, 이 명령은
어떤 것과도 일치하지 않습니다.
find bar -path /foo/bar/myfile -print
Find는 -path 인수를 디렉토리 이름과 검사하는 파일의 기본 이름을 연결한 것과 비교합니다.
연결은 슬래시로 끝나지 않으므로 슬래시로 끝나는 -path 인수는 아무것도 일치하지 않습니다(아마도 명령줄에 지정된 시작점을 제외하고). 술어 -path
는 HP-UX find에서도 지원되며 POSIX 2008
표준의 일부입니다.
-perm mode
파일의 권한 비트는 정확히 모드(8진수 또는 기호)입니다.
정확한 일치가 필요하므로 이 형식을 기호 모드에 사용하려는 경우 다소 복잡한
모드 문자열을 지정해야 할 수 있습니다. 예를 들어 `-perm g=w'는 모드가 0020인 파일(즉, 그룹 쓰기 권한이 유일한 권한 세트인 파일)만 일치합니다. `/' 또는 `-' 형식을 사용하고 싶을 가능성이 더 큽니다. 예를 들어 `-perm -g=w'는 그룹 쓰기 권한이 있는 모든 파일과 일치합니다. 몇 가지 설명적인 예는 EX‐
AMPLES 섹션을 참조하세요.
-perm -mode
모든 권한 비트 모드가 파일에 설정됩니다. 심볼릭
모드는 이 형식에서 허용되며, 이는 일반적으로
사용하려는 방식입니다. 심볼릭 모드를 사용하는 경우 `u', `g' 또는
`o'를 지정해야 합니다. 몇 가지 설명적인 예는 EXAMPLES 섹션을 참조하세요.
-perm /mode
모든 권한 비트 모드가 파일에 설정됩니다. 심볼릭
모드는 이 형식에서 허용됩니다. 심볼릭 모드를 사용하는 경우 `u', `g' 또는
`o'를 지정해야 합니다. 몇 가지 설명적인 예는 EXAMPLES 섹션을 참조하세요. 모드에 권한 비트가 설정되지 않은 경우 이 테스트는 모든 파일과 일치합니다(여기서 아이디어는 -perm -000의 동작과 일관되도록 하는 것입니다).
-perm +mode
더 이상 지원되지 않으며(2005년 이후로 사용되지 않음) 대신 -perm /mode를 사용하세요.
-readable
현재 사용자가 읽을 수 있는 파일과 일치합니다. 여기에는 -perm 테스트에서 무시하는 액세스 제어 목록 및 기타 권한 아티팩트가 고려됩니다. 이 테스트는
access(2) 시스템 호출을 사용하므로 UID 매핑(또는 루트 스쿼싱)을 수행하는 NFS 서버에 속을 수 있습니다. 많은 시스템이 클라이언트 커널에서 access(2)를 구현하여 서버에 보관된 UID 매핑 정보를 사용할 수 없기 때문입니다.
-regex pattern
파일 이름이 정규 표현식 패턴과 일치합니다. 이는 검색이 아닌 전체 경로와 일치합니다. 예를 들어, ./fubar3라는 이름의 파일을 일치시키려면 정규 표현식 `.*bar.' 또는 `.*b.*3'을 사용할 수 있지만 `f.*r3'은 사용할 수 없습니다. find에서 이해하는 정규 표현식은 기본적으로 Emacs 정규 표현식(단, `.'는 줄바꿈과 일치)이지만 -regex‐
type 옵션으로 변경할 수 있습니다.
-samefile name
파일은 name과 같은 inode를 참조합니다. -L이 적용되면
심볼릭 링크가 포함될 수 있습니다.
-size n[cwbkMG]
파일은 n 단위보다 적거나 많거나 정확히 n 단위의 공간을 사용하며,
반올림합니다. 다음 접미사를 사용할 수 있습니다.
`b'는 512바이트 블록(접미사를 사용하지 않는 경우 기본값)
`c'는 바이트
`w'는 2바이트 단어
`k'는 키비바이트(KiB, 1024바이트 단위)
`M'은 메비바이트(MiB, 1024 * 1024 = 1048576바이트 단위)
`G'는 기비바이트(GiB, 1024 * 1024 * 1024 = 1073741824바이트 단위)
크기는 lstat(또는 stat) 시스템 호출로 채워진 struct stat의 st_size 멤버이며, 위에 표시된 대로 반올림합니다. 즉, ls -l에 대한 결과와 일치합니다. -printf의 `%k' 및 `%b' 형식 지정자는 스파스 파일을 다르게 처리한다는 점을 명심하세요. `b' 접미사는 항상 512바이트 블록을 나타내며 1024바이트 블록을 나타내지 않습니다. 이는 -ls의 동작과 다릅니다.
+ 및 - 접두사는 평소와 같이 보다 크고 작음을 나타냅니다. 즉, n 단위의 정확한 크기는 일치하지 않습니다. 크기가 다음 단위로 반올림된다는 점을 명심하세요. 따라서
-size -1M은 -size -1048576c와 동일하지 않습니다. 전자는 빈 파일과만 일치하고 후자는 0~1,048,575바이트의 파일과 일치합니다.
-true 항상 참입니다.
-type c
파일의 유형은 c입니다.
b 블록(버퍼링됨) 특수
c 문자(버퍼링되지 않음) 특수
d 디렉토리
p 명명된 파이프(FIFO)
f 일반 파일
l 심볼릭 링크; -L 옵션이나 -follow 옵션이 적용되는 경우 심볼릭 링크가 끊어지지 않는 한 이는 절대 참이 아닙니다. -L이 적용되는 경우 심볼릭 링크를 검색하려면 -xtype을 사용합니다.
s 소켓
D 도어(Solaris)
한 번에 여러 유형을 검색하려면 쉼표 `,'로 구분된 유형 문자의 결합된 목록을 제공할 수 있습니다(GNU 확장).
-uid n 파일의 숫자 사용자 ID가 n보다 작거나, 크거나, 정확히 n입니다.
-used n
파일이 마지막으로 액세스된 날짜가 상태가 마지막으로 변경된 후 n일 이내이거나, n일 이상 또는 정확히 n일입니다.
-user uname
파일이 사용자 uname(숫자 사용자 ID 허용)의 소유입니다.
-wholename 패턴
-path를 참조하세요. 이 대안은 -path보다 이식성이 떨어집니다.
-writable
현재 사용자가 쓸 수 있는 파일을 찾습니다. 여기에는 -perm 테스트에서 무시하는 액세스 제어 목록 및 기타 권한 아티팩트가 고려됩니다. 이 테스트는
access(2) 시스템 호출을 사용하므로 UID 매핑(또는 루트 스쿼싱)을 수행하는 NFS 서버에 속을 수 있습니다. 많은 시스템이 클라이언트 커널에서 access(2)를 구현하여 서버에 보관된 UID 매핑 정보를 사용할 수 없기 때문입니다.
-xtype c
파일이 심볼릭 링크가 아닌 한 -type과 동일합니다. 심볼릭 링크의 경우: -H 또는 -P 옵션이 지정된 경우 파일이
유형 c의 파일에 대한 링크이면 true이고, -L 옵션이 지정된 경우
c가 `l'이면 true입니다. 즉, 심볼릭 링크의 경우
-xtype은 -type이 확인하지 않는 파일의 유형을 확인합니다.
-context pattern
(SELinux 전용) 파일의 보안 컨텍스트가 glob pattern‐ tern과 일치합니다.
동작
-delete
파일이나 디렉토리를 삭제합니다. 제거에 성공하면 true입니다. 제거에 실패하면 오류 메시지가 표시되고 find의 종료 상태가 0이 아닌 값이 됩니다(결국 종료될 때).
경고: find가 명령줄을 표현식으로 평가한다는 것을 잊지 마세요. 따라서 -delete를 먼저 지정하면 find가 지정한 시작점 아래의 모든 것을 삭제하려고 합니다.
명령줄에서 -delete 동작을 사용하면 자동으로 -depth 옵션이 켜집니다. -depth가 -prune을 비효과적으로 만들기 때문에 -delete 동작을 -prune과 유용하게 결합할 수 없습니다.
종종 사용자는 실제 제거 실행을 위해 -delete를 추가하기 전에 -print로 find 명령줄을 테스트하고 싶을 수 있습니다. 놀라운 결과를
피하기 위해 일반적으로 이전 테스트 실행 중에 -depth를 명시적으로 사용하는 것을 기억하는 것이 가장 좋습니다.
-delete 동작은 디렉토리가 비어 있지 않으면 디렉토리를 제거하지 못합니다.
-ignore_readdir_race 옵션과 함께 find는 부모 디렉토리를 읽은 후 파일이 사라진 경우 -delete 작업의 오류를 무시합니다. 오류 진단을 출력하지 않고 종료 코드를 0이 아닌 값으로 변경하지 않으며 -delete 작업의 반환 코드는 참입니다.
-exec 명령;
명령을 실행합니다. 0 상태가 반환되면 참입니다. find에 대한 모든 다음
인수는 `;'로 구성된 인수가 발생할 때까지 명령에 대한 인수로 간주됩니다. 문자열 `{}'는
명령에 대한 인수에서 발생하는 모든 곳에서 처리 중인 현재 파일 이름으로 대체되며, 일부 find 버전과 같이 인수에만 있는 것이 아닙니다. 이 두 가지
구문은 모두 이스케이프(`\'로)하거나 따옴표로 묶어 셸에서 확장되지 않도록 보호해야 할 수 있습니다. -exec 옵션 사용 예는 EXAMPLES 섹션을 참조하세요. 지정된
명령은 일치하는 각 파일에 대해 한 번씩 실행됩니다. 명령은 시작 디렉토리에서 실행됩니다. -exec 작업 사용에는 피할 수 없는 보안 문제가 있습니다. 대신 -execdir 옵션을 사용해야 합니다.
-exec 명령 {} +
-exec 작업의 이 변형은 지정된 명령을
선택한 파일에서 실행하지만 명령줄은
각 선택한 파일 이름을 끝에 추가하여 빌드됩니다. 명령의 총 호출 횟수는
일치하는 파일 수보다 훨씬 적습니다. 명령줄은 xargs가 명령줄을 빌드하는 것과 거의 같은 방식으로 빌드됩니다. 명령 내에서 `{}'의 인스턴스는 하나만 허용되며
끝에, `+' 바로 앞에 나타나야 합니다. 셸에서 해석되지 않도록 이스케이프(`\'로)하거나
따옴표로 묶어야 합니다.
명령은 시작 디렉토리에서 실행됩니다. `+' 형식의 호출이 종료 상태로 0이 아닌 값을 반환하면
find는 0이 아닌 종료 상태를 반환합니다. find에서
오류가 발생하면 이로 인해 즉시 종료될 수 있으므로 보류 중인 명령 중 일부가 전혀 실행되지 않을 수 있습니다. 이러한 이유로 -exec my-
command ... {} + -quit는 실제로 my-command가 실행되지 않을 수 있습니다. 이 -exec 변형은 항상 true를 반환합니다.
-execdir command ;
-execdir command {} +
-exec와 유사하지만 지정된 명령은 일치하는 파일이 포함된 하위 디렉토리에서 실행되며, 이는 일반적으로 find를 시작한 디렉토리가 아닙니다. -exec와 마찬가지로 find가 셸에서 호출되는 경우 {}를 따옴표로 묶어야 합니다. 이는 일치하는 파일에 대한 경로를 확인하는 동안 경쟁 조건을 피하기 때문에 명령을 호출하는 훨씬 더 안전한 방법입니다. -exec 작업과 마찬가지로 -execdir의 `+' 형식은 여러 개의 일치하는 파일을 처리하는 명령줄을 빌드하지만 주어진 command 호출은 동일한 하위 디렉토리에 있는 파일만 나열합니다. 이 옵션을 사용하는 경우 PATH 환경 변수가 `.'을 참조하지 않도록 해야 합니다. 그렇지 않으면 공격자는 -execdir을 실행할 디렉토리에 적절한 이름의 파일을 남겨두어 원하는 명령을 실행할 수 있습니다. PATH에 비어 있거나 절대 디렉토리 이름이 아닌 항목이 있는 경우에도 마찬가지입니다. `+' 형식의 호출이 종료 상태로 0이 아닌 값을 반환하면
find는 0이 아닌 종료 상태를 반환합니다. find에서
오류가 발생하면 이로 인해 즉시 종료될 수 있으므로 보류 중인 일부 명령이 전혀 실행되지 않을 수 있습니다. 작업의 결과는 + 또는 ; 변형을 사용하는지 여부에 따라 달라집니다. -ex‐
ecdir command {} +는 항상 true를 반환하는 반면 -execdir command {} ;는 command가 0을 반환하는 경우에만 true를 반환합니다.
-fls file
True; -ls와 유사하지만 -fprint와 유사하게 파일에 씁니다. 출력 파일은
술어가 일치하지 않더라도 항상 생성됩니다.
파일 이름의 비정상적인 문자가 처리되는 방법에 대한 자세한 내용은 UNUSUAL FILENAMES 섹션을 참조하세요.
-fprint file
True; 전체 파일 이름을 file 파일에 인쇄합니다. find를 실행할 때 file이
없으면 생성됩니다. 있으면 잘립니다. 파일 이름 /dev/stdout 및 /dev/stderr은 특별히 처리됩니다. 각각 표준 출력 및 표준
오류 출력을 참조합니다. 출력 파일은 술어가 일치하지 않더라도 항상 생성됩니다.
파일 이름의 비정상적인 문자가 처리되는 방법에 대한 자세한 내용은 UNUSUAL FILENAMES 섹션을 참조하세요.
-fprint0 file
True; -print0과 유사하지만 -fprint와 유사하게 file에 씁니다. 출력 파일은 술어가 일치하지 않더라도 항상 생성됩니다.
파일 이름의 비정상적인 문자가 처리되는 방법에 대한 자세한 내용은 UNUSUAL FILENAMES 섹션을 참조하세요.
-fprintf 파일 형식
True; -printf와 비슷하지만 -fprint와 비슷하게 파일에 씁니다. 술어가 일치하지 않더라도 출력
파일은 항상 생성됩니다.
파일 이름의 비정상적인 문자가 처리되는 방법에 대한 자세한 내용은 UNUSUAL FILENAMES 섹션을 참조하세요.
-ls True; 표준 출력에 ls -dils 형식으로 현재 파일을 나열합니다.
환경 변수 POSIXLY_CORRECT가 설정되지 않은 경우 블록 수는 1KB 블록이며, 설정된 경우 512바이트 블록이 사용됩니다.
파일 이름의 비정상적인 문자가 처리되는 방법에 대한 자세한 내용은 UNUSUAL FILENAMES 섹션을 참조하세요.
-ok 명령;
-exec와 비슷하지만 사용자에게 먼저 묻습니다. 사용자가 동의하면
명령을 실행합니다. 그렇지 않으면 false를 반환합니다. 명령이 실행되면
표준 입력이 /dev/null에서 리디렉션됩니다. 이 작업은
-files0-from 옵션과 함께 지정할 수 없습니다.
프롬프트에 대한 응답은 정규 표현식 쌍과 일치하여 긍정 응답인지 부정 응답인지 판별합니다. 이 정규 표현식은 POSIXLY_CORRECT 환경 변수가 설정된 경우 시스템에서 가져오고, 그렇지 않으면
find의 메시지 번역에서 가져옵니다. 시스템에 적합한
정의가 없으면 find의 자체 정의가 사용됩니다. 어느 경우든
정규 표현식 자체의 해석은 환경 변수 LC_CTYPE(문자 클래스)
및 LC_COLLATE(문자 범위 및 동등 클래스)의 영향을 받습니다.
-okdir 명령;
-execdir와 비슷하지만 -ok와 같은 방식으로 사용자에게 먼저 묻습니다.
사용자가 동의하지 않으면 false를 반환하면 됩니다. 명령이 실행되면 표준 입력이 /dev/null에서 리디렉션됩니다. 이
작업은 -files0-from 옵션과 함께 지정할 수 없습니다.
-print True; 표준 출력에 전체 파일 이름을 인쇄한 다음 줄바꿈을 붙입니다. find의 출력을 다른
프로그램으로 파이프하고 검색하는 파일에 줄바꿈이 포함되어 있을 가능성이 조금이라도 있다면 -print 대신 -print0 옵션을 사용하는 것을 진지하게 고려해야 합니다.
파일 이름에서 비정상적인 문자가 처리되는 방법에 대한 자세한 내용은 UNUSUAL FILENAMES 섹션을 참조하세요.
-print0
True; 표준 출력에 전체 파일 이름을 인쇄한 다음 줄바꿈 문자 대신 null 문자를 붙입니다. 이렇게 하면 줄바꿈이나
다른 유형의 공백이 포함된 파일 이름을 find 출력을 처리하는 프로그램에서 올바르게 해석할 수 있습니다. 이 옵션은 xargs의 -0 옵션에 해당합니다.
-printf 형식
True; 표준 출력에 형식을 인쇄하고 `\' 이스케이프와 `%' 지시어를 해석합니다. 필드 너비와 정밀도는
printf(3) C 함수와 같이 지정할 수 있습니다.
많은 필드가 %d가 아닌 %s로 인쇄된다는 점에 유의하세요. 이는
플래그가 예상대로 작동하지 않을 수 있음을 의미합니다. 또한
`-' 플래그가 작동한다는 것을 의미합니다(필드를 왼쪽 정렬하도록 강제). -print와 달리 -printf는 문자열 끝에 줄 바꿈을 추가하지 않습니다.
이스케이프와 지시어는 다음과 같습니다.
\a 경고음.
\b 백스페이스.
\c 이 형식에서 즉시 인쇄를 중지하고
출력을 플러시합니다.
\f 폼 피드.
\n 줄 바꿈.
\r 캐리지 리턴.
\t 가로 탭.
\v 세로 탭.
\0 ASCII NUL.
\\ 리터럴 백슬래시(`\').
\NNN ASCII 코드가 NNN(8진수)인 문자.
다른 문자 뒤에 `\' 문자가 오면 일반 문자로 처리되므로 둘 다 인쇄됩니다.
%% 리터럴 퍼센트 기호.
%a C ctime(3) 함수에서 반환한 형식의 파일 마지막 액세스 시간.
%Ak `@' 또는 C strftime(3) 함수에 대한 지시어인 k로 지정한 형식의 파일 마지막 액세스 시간.
다음은 k에 대한 가능한 값의 불완전한 목록입니다. 전체 목록은
strftime(3) 설명서를 참조하십시오. 일부 변환
사양 문자는 strftime(3) 라이브러리 함수 구현의 차이로 인해 모든 시스템에서 사용할 수 없을 수 있습니다.
@ 1970년 1월 1일 00:00 GMT 이후의 초, 소수 부분 포함.
시간 필드:
H 시간(00..23)
I 시간(01..12)
k 시간(0..23)
l 시간(1..12)
M 분(00..59)
p 로케일의 AM 또는 PM
r 시간, 12시간제(hh:mm:ss [AP]M)
S 초(00.00 .. 61.00). 소수 부분이 있습니다.
T 시간, 24시간제(hh:mm:ss.xxxxxxxxxx)
+ 날짜 및 시간은 `+'로 구분합니다. 예:
`2004-04-28+22:22:05.0'. 이것은 GNU 확장입니다.
시간은 현재 시간대로 제공됩니다(TZ 환경 변수를 설정하면 영향을 받을 수 있음). 초 필드에는 소수 부분이 포함됩니다.
X 로케일의 시간 표현(H:M:S). 초
필드에는 소수 부분이 포함됩니다.
Z 시간대(예: EDT) 또는 시간대를 결정할 수 없는 경우 아무것도 없음
날짜 필드:
a 로케일의 약식 요일 이름(일요일..토요일)
a 로케일의 전체 요일 이름, 가변 길이(일요일..토요일)
b 로케일의 약식 월 이름(1월..12월)
B 로케일의 전체 월 이름, 가변 길이(1월..12월)
c 로케일의 날짜 및 시간(토요일 11월 04일 12:02:33 EST
1989). 형식은 ctime(3)과 동일하므로
해당 형식과의 호환성을 유지하기 위해 초 필드에 소수 부분이 없습니다.
d 월 일자(01..31)
D 날짜(mm/dd/yy)
F 날짜(yyyy-mm-dd)
h b와 동일
j 일자(001..366)
m 월(01..12)
U 일요일을 첫 번째 요일로 하는 연도 주 번호(00..53)
w 요일(0..6)
W 월요일을 첫 번째 요일로 하는 연도 주 번호(00..53)
x 로케일의 날짜 표현(mm/dd/yy)
y 연도의 마지막 두 자리(00..99)
Y 연도(1970...)
%b 이 파일에 사용된 디스크 공간의 양(512바이트
블록). 디스크 공간은 파일 시스템 블록 크기의 배수로 할당되므로 일반적으로 %s/512보다 크지만 파일이 스파스 파일인 경우 더 작을 수도 있습니다.
%Bk 파일의 생성 시간, 즉 k로 지정된 형식으로 된 생성 시간으로, %A와 동일합니다. 이 지시문은 기본 운영 체제 또는 파일 시스템이 생성 시간을 지원하지 않으면 빈 문자열을 생성합니다.
%c C ctime(3) 함수에서 반환한 형식으로 된 파일의 마지막 상태 변경 시간입니다.
%Ck k로 지정된 형식으로 된 파일의 마지막 상태 변경 시간으로, %A와 동일합니다.
%d 디렉토리 트리에서 파일의 깊이입니다. 0은 파일이 시작점임을 의미합니다.
%D 파일이 있는 장치 번호(struct stat의 st_dev
필드)로, 10진수입니다.
%f 기본 이름을 인쇄합니다. 선행 디렉토리를 제거한 파일 이름(마지막 요소만). /의 경우 결과는 `/'입니다. 예제는 EXAMPLES 섹션을 참조하세요.
%F 파일이 있는 파일 시스템의 유형입니다. 이 값은 -fstype에 사용할 수 있습니다.
%g 파일의 그룹 이름 또는 그룹에 이름이 없는 경우 숫자 그룹 ID입니다.
%G 파일의 숫자 그룹 ID입니다.
%h 디렉토리 이름; 파일 이름의 선행 디렉토리(마지막 요소를 제외한 모든 디렉토리). 파일 이름에 슬래시가 없는 경우(현재 디렉토리에 있기 때문) %h 지정자는 `.'으로 확장됩니다. 디렉토리 자체이고 슬래시(/ 포함)가 있는 파일의 경우 %h는 빈 문자열로 확장됩니다. 예제는 EXAMPLES 섹션을 참조하세요.
%H 파일이 발견된 시작점.
%i 파일의 inode 번호(10진수).
%k 1KB 블록에서 이 파일에 사용된 디스크 공간의 양.
디스크 공간은 파일 시스템 블록 크기의 배수로 할당되므로 일반적으로 %s/1024보다 크지만 파일이 스파스 파일인 경우 더 작을 수도 있습니다.
%l 심볼릭 링크의 개체(파일이 심볼릭 링크가 아닌 경우 빈 문자열).
%m 파일의 권한 비트(8진수). 이 옵션은 대부분 Unix 구현에서 사용하는
`전통적인' 숫자를 사용하지만 특정 구현에서 8진수 권한 비트의 비정상적인 순서를 사용하는 경우 파일 모드의 실제 값과 %m의 출력 사이에 차이가 있습니다. 일반적으로 이 숫자 앞에 0이 있어야 하며, 이를 위해 # 플래그를 사용해야 합니다(예: `%#m').
%M 파일 권한(ls의 경우와 같이 심볼릭 형태). 이
지시어는 findutils 4.2.5 이상에서 지원됩니다.
%n 파일에 대한 하드 링크 수.
%p 파일 이름.
%P 파일 이름에 발견된 시작점 이름을 제거한
파일 이름.
%s 바이트 단위의 파일 크기.
%S 파일의 희소성. 이는 (BLOCK‐
SIZE*st_blocks / st_size)로 계산됩니다. 특정 길이의 일반 파일에 대해 얻을 정확한 값은
시스템에 따라 다릅니다. 그러나 일반적으로 희소 파일은 1.0보다 작은 값을
가지며 간접 블록을 사용하는 파일은 1.0보다 큰 값을 가질 수 있습니다. 일반적으로
파일에서 사용하는 블록 수는 파일 시스템에 따라 다릅니다.
BLOCKSIZE에 사용되는 값은 시스템에 따라 다르지만
일반적으로 512바이트입니다. 파일 크기가 0이면 인쇄된 값은 정의되지 않습니다. st_blocks를 지원하지 않는 시스템에서는 파일의 희소성이 1.0으로 가정합니다.
%t C ctime(3) 함수에서 반환한 형식의 파일의 마지막 수정 시간입니다.
%Tk k에서 지정한 형식의 파일의 마지막 수정 시간으로, %A와 동일합니다.
%u 파일의 사용자 이름 또는 사용자에게 이름이 없는 경우 숫자 사용자 ID입니다.
%U 파일의 숫자 사용자 ID입니다.
%y 파일의 유형(ls -l과 같음), U=알 수 없는 유형(발생해서는 안 됨)
%Y 파일의 유형(%y와 같음), 심볼릭 링크를 따릅니다.
`L'=루프, `N'=존재하지 않음, `?' 심볼릭 링크의 대상 유형을 결정할 때 다른 오류가 있는 경우
%Z(SELinux 전용) 파일의 보안 컨텍스트입니다.
%{ %[ %(
향후 사용을 위해 예약됨.
`%' 문자 뒤에 다른 문자가 오면 삭제되지만,
다른 문자는 인쇄됩니다(추가 형식 문자가 추가될 수 있으므로 이에 의존하지 마세요). 형식 인수 끝에 `%'가 있으면 다음 문자가 없기 때문에 정의되지 않은 동작이 발생합니다. 일부 로캘에서는 문 열쇠를 숨길 수 있고, 다른 로캘에서는 읽고 있는 소설의 마지막 페이지를 제거할 수 있습니다.
%m 및 %d 지시문은 #, 0 및 + 플래그를 지원하지만, 다른 지시문은 숫자를 인쇄하더라도 지원하지 않습니다. 이러한 플래그를 지원하지 않는 숫자
지시문에는 G, U, b, D, k 및 n이 있습니다. `-' 형식 플래그는 지원되며 필드의 정렬을 오른쪽 정렬(기본값)에서 왼쪽 정렬로 변경합니다.
파일 이름의 비정상적인 문자가 처리되는 방법에 대한 자세한 내용은 비정상적인 파일 이름 섹션을 참조하세요.
-prune True; 파일이 디렉토리인 경우, 그 디렉토리로 내려가지 마십시오. -depth가 주어지면 -prune은 효과가 없습니다. -delete는 -depth를 의미하므로 -prune과 -delete를 함께 유용하게 사용할 수 없습니다. 예를 들어, src/emacs 디렉토리와 그 아래의 모든
파일과 디렉토리를 건너뛰고, 발견된 다른
파일의 이름을 인쇄하려면 다음과 같이 하십시오.
find . -path ./src/emacs -prune -o -print
-quit 즉시 종료합니다(오류가 발생하지 않으면 반환 값 0). 이것은 -prune과 다릅니다. -prune은 정리된 디렉토리의 내용에만 적용되는 반면 -quit은
find를 즉시 중지하기 때문입니다. 실행 중인 자식 프로세스는 없습니다. -exec ... +
또는 -execdir ... +로 빌드된 모든 명령줄은 프로그램이 종료되기 전에 호출됩니다. -quit이 실행된 후에는 명령줄에 지정된 더 이상 파일이 처리되지 않습니다. 예를 들어,
`find /tmp/foo /tmp/bar -print -quit`는
`/tmp/foo`만 인쇄합니다.
-quit의 일반적인 용도 중 하나는 원하는 것을 찾은 후 파일 시스템 검색을 중지하는 것입니다.
예를 들어, 단일 파일만 찾으려면 다음과 같이 할 수 있습니다.
find / -name needle -print -quit
연산자
우선순위가 감소하는 순서대로 나열:
( expr )
우선순위를 강제합니다. 괄호는 셸에서 특별한 것이므로
일반적으로 따옴표로 묶어야 합니다. 이 매뉴얼 페이지의 많은 예에서 이 목적을 위해 백슬래시를 사용합니다: `(...)' 대신 `\(...\)'.
! expr expr이 거짓이면 참입니다. 이 문자는 일반적으로
셸에서 해석되지 않도록 보호해야 합니다.
-not expr
! expr과 동일하지만 POSIX 호환이 아닙니다.
expr1 expr2
연속된 두 표현식은 묵시적으로
-a; expr1이 거짓이면 expr2가 평가되지 않습니다.
expr1 -a expr2
expr1 expr2와 동일합니다.
expr1 -and expr2
expr1 expr2와 동일하지만 POSIX 호환이 아닙니다.
expr1 -o expr2
또는; expr1이 참이면 expr2는 평가되지 않습니다.
expr1 -or expr2
expr1 -o expr2와 동일하지만 POSIX 호환은 아닙니다.
expr1 , expr2
목록; expr1과 expr2는 항상 평가됩니다.
expr1의 값은 삭제되고 목록의 값은 expr2의 값입니다.
쉼표 연산자는 여러 가지 다른 유형의 항목을 검색하는 데 유용할 수 있지만 파일 시스템 계층을 한 번만 탐색합니다. -fprintf 작업을 사용하여 다양한
일치 항목을 여러 다른 출력 파일에 나열할 수 있습니다.
-a가 암묵적으로 지정되거나(예: 두 테스트가 명시적 연산자 없이 나타나는 경우) 또는 명시적으로 지정되면 -o보다 우선순위가 높습니다. 즉, find . -name afile -o -name
bfile -print는 afile을 인쇄하지 않습니다.
비정상적인 파일 이름
find의 많은 동작은 다른 사용자가 제어하는 데이터를 인쇄하는 결과를 낳습니다. 여기에는 파일 이름, 크기, 수정 시간 등이 포함됩니다. 파일 이름은 `\0' 및 `/'를 제외한 모든 문자를 포함할 수 있기 때문에 잠재적인 문제가 될 수 있습니다. 파일 이름에 있는 비정상적인 문자는
터미널에 예상치 못한, 종종 바람직하지 않은 일을 할 수 있습니다(예: 일부 터미널에서 기능 키 설정 변경). 비정상적인 문자는 아래에 설명된 대로 다양한 동작에 따라 다르게 처리됩니다.
-print0, -fprint0
출력이 터미널로 가는 경우에도 항상 정확한 파일 이름을 변경하지 않고 인쇄합니다.
-ls, -fls
비정상적인 문자는 항상 이스케이프됩니다. 공백, 백슬래시,
및 큰따옴표 문자는 C 스타일 이스케이프를 사용하여 인쇄합니다(예: `\f', `\"'). 다른 비정상적인 문자는 8진수 이스케이프를 사용하여 인쇄합니다. 다른 인쇄 가능한 문자(-ls 및
-fls의 경우 8진수 041과 0176 사이의 문자)는
있는 그대로 인쇄합니다.
-printf, -fprintf
출력이 터미널로 전송되지 않으면 있는 그대로 인쇄합니다.
그렇지 않으면 결과는 사용 중인 지시문에 따라 달라집니다.
지시문 %D, %F, %g, %G, %H, %Y 및 %y는 파일 소유자의 제어를 받지 않는 값으로 확장되므로 있는 그대로 인쇄합니다.
지시문 %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t,
%u 및 %U는 파일 소유자의 제어를 받지만 임의의 데이터를 터미널에 전송하므로 그대로 인쇄됩니다. %f, %h, %l, %p 및 %P 지시어는 인용됩니다. 이 인용은 GNU ls와 같은 방식으로 수행됩니다. 이것은 -ls 및 -fls에 사용된 것과 동일한 인용 메커니즘이 아닙니다. find의 출력에 사용할 형식을 결정할 수 있다면 일반적으로 줄바꿈을 사용하는 것보다 `\0'을 종료자로 사용하는 것이 더 좋습니다. 파일 이름에는 공백과 줄바꿈 문자가 포함될 수 있기 때문입니다. LC_CTYPE 환경 변수의 설정은 어떤 문자를 인용해야 하는지 결정하는 데 사용됩니다.
-print, -fprint
인용은 -printf 및 -fprintf와 같은 방식으로 처리됩니다.
스크립트에서 find를 사용하거나 일치하는 파일의 이름이 임의일 수 있는 상황에서 -print 대신 -print0을 사용하는 것을 고려해야 합니다.
-ok 및 -okdir 작업은 현재 파일 이름을 그대로 인쇄합니다. 이는 향후 릴리스에서 변경될 수 있습니다.
표준 준수
POSIX 표준을 가장 잘 준수하려면 POSIXLY_CORRECT 환경 변수를 설정해야 합니다. 다음 옵션은 POSIX 표준(IEEE Std 1003.1-2008, 2016 Edition)에 지정되어 있습니다.
-H 이 옵션은 지원됩니다.
-L 이 옵션은 지원됩니다.
-name 이 옵션은 지원되지만 POSIX 준수는 시스템의 fnmatch(3) 라이브러리 함수의
POSIX 준수에 따라 달라집니다.
findutils-4.2.2부터 셸 메타문자(예: `*', `?' 또는 `[]')는 선행 `.'과 일치합니다. IEEE PASC 해석 126에서 이를 요구하기 때문입니다. 이는 이전 버전의 findutils에서 변경된 사항입니다.
-type 지원됨. POSIX는 `b', `c', `d', `l', `p', `f' 및
`s'를 지정합니다. GNU find는 Door를 나타내는 `D'도 지원하며, 여기서는
OS가 제공합니다. 게다가 GNU find는 여러 유형을 쉼표로 구분된 목록에서 한 번에 지정할 수 있도록 합니다.
-ok 지원됨. 응답의 해석은 LC_MESSAGES 환경 변수를 설정하여 선택한 `yes' 및 `no' 패턴에 따릅니다. POSIXLY_CORRECT 환경 변수가 설정되면 이러한 패턴은 시스템의
긍정적(예) 또는 부정적(아니요) 응답 정의에서 가져옵니다. nl_langinfo(3)에 대한 시스템 설명서를 참조하세요. 특히 YESEXPR 및 NOEXPR에 대해 알아보세요.
POSIXLY_CORRECT가 설정되지 않으면 패턴은 대신 find의 자체 메시지 카탈로그에서 가져옵니다.
-newer 지원됨. 지정된 파일이 심볼릭 링크인 경우 항상 역참조됩니다. 이는 심볼릭 링크에서 관련 시간을 가져가던 이전 동작에서 변경된 것입니다. 참조
아래의 HISTORY 섹션.
-perm 지원. POSIXLY_CORRECT 환경 변수가 설정되지 않은 경우
POSIX에서 유효하지 않은 일부 모드 인수(예: +a+x)가 이전 버전과의 호환성을 위해 지원됩니다.
기타 기본
기본 -atime, -ctime, -depth, -exec, -group, -links,
-mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size,
-user 및 -xdev는 모두 지원됩니다.
POSIX 표준은 괄호 `(', `)', 부정 `!' 및
논리적 AND/OR 연산자 -a 및 -o를 지정합니다.
다른 모든 옵션, 술어, 표현식 등은 POSIX 표준을 벗어난 확장입니다.
그러나 이러한 확장 중 다수는 GNU find에만 국한되지 않습니다.
POSIX 표준은 find가 루프를 감지하도록 요구합니다.
find 유틸리티는 무한 루프를 감지해야 합니다. 즉, 마지막으로 발견한 파일의 조상인 이전에 방문한 디렉토리를 입력합니다. 무한 루프를 감지하면 find는 표준 오류에 진단 메시지를 쓰고 계층 구조에서 위치를 복구하거나 종료합니다.
GNU find는 이러한 요구 사항을 준수합니다. 조상에 대한 하드 링크인 항목이 포함된 디렉토리의 링크 수는 그렇지 않은 경우보다 종종 낮습니다. 즉, GNU find는 실제로 조상에 대한 링크인 하위 디렉토리 방문을 최적화하지 않을 수 있습니다. find는 실제로 이러한 하위 디렉토리에 들어가지 않으므로 진단 메시지를 내보내지 않아도 됩니다. 이러한 동작은 다소 혼란스러울 수 있지만 실제로 누군가가 이 동작에 의존할 가능성은 낮습니다. -noleaf로 리프 최적화가 꺼진 경우 디렉토리 항목은 항상 검사되고 진단 메시지는 적절한 곳에서 발행됩니다. 심볼릭 링크는 그 자체로 파일 시스템 사이클을 만드는 데 사용할 수 없지만 -L 옵션이나 -follow 옵션이 사용 중인 경우 find가 심볼릭 링크 루프를 만나면 진단 메시지가 발행됩니다. 하드 링크가 포함된 루프와 마찬가지로 리프 최적화는
종종 find가 심볼릭 링크에서 stat() 또는
chdir()를 호출할 필요가 없다는 것을 알고 있음을 의미하므로 이 진단은 종종 필요하지 않습니다.
-d 옵션은 다양한 BSD 시스템과의 호환성을 위해 지원되지만
대신 POSIX 호환 옵션인 -depth를 사용해야 합니다.
POSIXLY_CORRECT 환경 변수는 -regex 또는 -iregex 테스트의 동작에 영향을 미치지 않습니다. 이러한 테스트는
POSIX 표준에 지정되어 있지 않기 때문입니다.
환경 변수
LANG 설정되지 않았거나 null인 국제화 변수에 대한 기본값을 제공합니다.
LC_ALL 비어 있지 않은 문자열 값으로 설정된 경우 다른 모든 국제화 변수의 값을 재정의합니다.
LC_COLLATE
POSIX 표준은 이 변수가 -name 옵션에 사용되는 패턴 매칭에 영향을 미친다고 명시합니다. GNU find는
fnmatch(3) 라이브러리 함수를 사용하므로 LC_COLLATE에 대한 지원은
시스템 라이브러리에 따라 달라집니다. 이 변수는 또한 -ok에 대한 응답의
해석에도 영향을 미칩니다. LC_MESSAGES
변수는 -ok에 대한 응답을 해석하는 데 사용되는 실제 패턴을 선택하는 반면, 패턴의 모든 대괄호 표현식의 해석은 LC_COLLATE의 영향을 받습니다.
LC_CTYPE
이 변수는 정규 표현식에서 사용되는 문자 클래스의 처리에 영향을 미치며, 시스템의 fnmatch(3) 라이브러리 함수가 이를 지원하는 경우 -name 테스트에도 영향을 미칩니다. 이 변수는 또한 -ok에서 발행한 프롬프트에 대한 응답을 해석하는 데 사용되는 정규 표현식의 모든 문자 클래스의 해석에도 영향을 미칩니다. LC_CTYPE 환경 변수는 또한 파일 이름을 인쇄할 때 인쇄할 수 없는 것으로 간주되는 문자에 영향을 미칩니다. 비정상적인 파일 이름 섹션을 참조하세요.
LC_MESSAGES
국제화된 메시지에 사용할 로캘을 결정합니다.
POSIXLY_CORRECT 환경 변수가 설정된 경우 -ok 작업에서 만든 프롬프트에 대한 응답의 해석도 결정합니다.
NLSPATH
국제화 메시지 카탈로그의 위치를 결정합니다.
PATH는 -exec, -execdir, -ok 및 -okdir에서 호출한 실행 파일을 찾기 위해 검색하는 디렉토리에 영향을 미칩니다.
POSIXLY_CORRECT
-ls 및 -fls에서 사용하는 블록 크기를 결정합니다. POSIXLY_CORRECT가 설정된 경우 블록은 512바이트 단위입니다. 그렇지 않으면 1024바이트 단위입니다.
이 변수를 설정하면 기본적으로 경고 메시지(즉, -nowarn을 의미)도 꺼집니다. POSIX에서는 -ok에 대한 출력과 별도로 stderr에 인쇄된 모든 메시지가 진단 불가능하고 0이 아닌 종료 상태가 되어야 하기 때문입니다.
POSIXLY_CORRECT가 설정되지 않은 경우 -perm +zzz는 +zzz가 유효한 심볼릭 모드가 아닌 경우 -perm /zzz와 마찬가지로 처리됩니다.
POSIXLY_CORRECT가 설정된 경우 이러한 구성 요소는 오류로 처리됩니다.
POSIXLY_CORRECT가 설정된 경우 -ok 작업에서 프롬프트에 대한 응답은 find 자체의 메시지 번역이 아닌 시스템 메시지 카탈로그에 따라 해석됩니다.
TZ -printf 및 -fprintf의 일부 시간 관련 형식 지시문에 사용되는 시간대에 영향을 미칩니다.
예
간단한 `find|xargs` 접근법
• 디렉토리 /tmp 또는 그 아래에서 core라는 이름의 파일을 찾아 삭제합니다.
$ find /tmp -name core -type f -print | xargs /bin/rm -f
줄바꿈, 작은따옴표나 큰따옴표, 공백이 포함된 파일 이름이 있는 경우 이 방법이 제대로 작동하지 않습니다.
더 안전한 `find -print0 | xargs -0` 접근법
• 디렉토리 /tmp 또는 그 아래에서 core라는 이름의 파일을 찾아 삭제합니다. 작은따옴표나 큰따옴표, 공백 또는 줄바꿈이 포함된 파일이나 디렉토리 이름이 올바르게 처리되도록 파일 이름을 처리합니다.
$ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f
-name 테스트는 모든 파일에서 stat(2)를 호출하지 않아도 되도록 -type 테스트보다 먼저 옵니다.
find가 계층을 탐색하여 일치하는 파일 이름을 인쇄하는 시간과 xargs가 실행한 프로세스가 해당 파일을 처리하는 시간 사이에 여전히 경쟁이 있다는 점에 유의하세요.
임의의 시작점 처리
• 다른 프로그램 proggy가 사전 필터링하여 거대한
NUL로 구분된 파일 목록을 생성한다는 점을 감안하여 이를 시작점으로 처리하고
그 중에서 모든 일반 빈 파일을 찾습니다.
$ proggy | find -files0-from - -maxdepth 0 -type f -empty
`-files0-from -`를 사용하면 표준 입력, 즉 파이프에서 시작점의 이름을 읽고
-maxdepth 0을 사용하면 재귀적으로 디렉터리로 이동하지 않고(시작점 중 하나가 하나인 경우) 해당 항목만 명시적으로 검사합니다.
각 파일에 대한 명령 실행
• 현재 디렉터리 또는 그 아래에 있는 모든 파일에 대해 file을 실행합니다.
$ find . -type f -exec file '{}' \;
중괄호는 셸 스크립트 구두점으로 해석되는 것을 방지하기 위해 작은따옴표로 묶였습니다.
세미콜론은 백슬래시를 사용하여 비슷하게 보호되지만
작은따옴표도 그 경우에 사용할 수 있습니다.
많은 경우 성능과 보안상의 이유로 `-exec ... +` 또는 더 나은 `-ex‐
ecdir ... +` 구문을 선호할 수 있습니다.
파일 시스템을 한 번만 탐색 - 2가지 다른 작업
• 파일 시스템을 한 번만 탐색하여 set-user-ID 파일과
디렉토리를 /root/suid.txt에 나열하고 큰 파일을
/root/big.txt에 나열합니다.
$ find / \
\( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \
\( -size +100M -fprintf /root/big.txt '%-10s %p\n' \)
이 예에서는 첫 두 줄에 줄 연속 문자 '\'를 사용하여 셸에 다음 줄에서
명령을 계속 읽도록 지시합니다.
나이로 파일 검색
• 홈 디렉토리에서 지난 24시간 동안 수정된 파일을 검색합니다.
$ find $HOME -mtime 0
이 명령은 각 파일이 마지막으로 수정된 이후의 시간을 24시간으로 나누고 나머지는 삭제하기 때문에 이런 방식으로 작동합니다. 즉, -mtime 0과 일치하려면 파일이
24시간 이내에 수정되어야 합니다.
권한으로 파일 검색
• 실행 가능하지만 읽을 수 없는 파일을 검색합니다.
$ find /sbin /usr/sbin -executable \! -readable -print
• 소유자와 그룹에 대한 읽기 및 쓰기 권한이 있지만 다른 사용자는 읽을 수 있지만 쓸 수 없는 파일을 검색합니다.
$ find . -perm 664
이러한 기준을 충족하지만 다른 권한 비트가 설정된 파일(예: 누군가가 파일을 실행할 수 있는 경우)은
일치하지 않습니다.
• 소유자와 그룹에 대한 읽기 및 쓰기 권한이 있고 다른 사용자가 추가 권한 비트(예: 실행 비트)의 존재 여부와 관계없이 읽을 수 있는 파일을 검색합니다.
$ find . -perm -664
예를 들어 모드가 0777인 파일과 일치합니다.
• 누군가(소유자, 그룹 또는 다른 사람)가 쓸 수 있는 파일을 검색합니다.
$ find . -perm /222
• 소유자 또는 그룹이 쓸 수 있는 파일을 검색합니다.
$ find . -perm /220
$ find . -perm /u+w,g+w
$ find . -perm /u=w,g=w
이 세 가지 명령은 모두 같은 작업을 수행하지만 첫 번째 명령은
파일 모드의 8진수 표현을 사용하고 다른 두 명령은
기호 형식을 사용합니다. 파일은 일치하기 위해 소유자와 그룹 모두가 쓸 수 있어야 하는 것은 아닙니다. 둘 다 가능합니다.
• 소유자와 그룹 모두가 쓸 수 있는 파일을 검색합니다.
$ find . -perm -220
$ find . -perm -g+w,u+w
두 명령 모두 같은 작업을 수행합니다.
• 권한에 대한 보다 정교한 검색.
$ find . -perm -444 -perm /222 \! -perm /111
$ find . -perm -a+r -perm /a+w \! -perm /a+x
두 명령 모두 모든 사람이 읽을 수 있는 파일(-perm -444 또는 -perm -a+r), 최소한 하나의 쓰기 비트가 설정된 파일(-perm /222 또는 -perm /a+w)을 검색하지만 아무에게도 실행할 수 없는 파일(각각 ! -perm /111 또는 ! -perm /a+x)을 검색합니다.
가지치기 - 파일 및 하위 디렉터리 생략
• /source-dir의 내용을 /dest-dir에 복사하지만 .snapshot(및 그 안에 있는 모든 것)이라는 이름의 파일과 디렉터리는 생략합니다. 또한 이름이 `~'로 끝나는 파일이나 디렉터리는 생략하지만 그 내용은 생략하지 않습니다.
$ cd /source-dir
$ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \
| cpio -pmd0 /dest-dir
-prune -o \( ... -print0 \) 구문은 꽤 일반적입니다.
여기서 아이디어는 -prune 앞의 표현식이 가지치기될 것과 일치한다는 것입니다.
그러나 -prune 작업 자체가 true로 반환되므로 다음 -o는 오른쪽이 가지치기되지 않은 디렉터리에 대해서만 평가되도록 합니다.
(가지치기된 디렉터리의 내용은 방문조차 하지 않으므로 그 내용은 중요하지 않습니다). -o의 오른쪽에 있는 표현식은 명확성을 위해 괄호로만 묶었습니다. -print0 동작은 -prune이 적용되지 않은 것에 대해서만 수행된다는 것을 강조합니다. 테스트 간의 기본 `and' 조건이 -o보다 더 긴밀하게 결합되기 때문에 이것이 기본 조건이지만 괄호는 무슨 일이 일어나고 있는지 보여주는 데 도움이 됩니다.
• 다음 프로젝트 디렉토리와 관련
SCM 관리 디렉토리가 주어지면, 프로젝트의 루트에 대한 효율적인 검색을 수행합니다.
$ find repo/ \
\( -exec test -d '{}/.svn' \; \
-or -exec test -d '{}/.git' \; \
-or -exec test -d '{}/CVS' \; \
\) -print -prune
샘플 출력:
repo/project1/CVS
repo/gnu/project2/.svn
repo/gnu/project3/.svn
repo/gnu/project3/src/.svn
repo/project4/.git
이 예에서 -prune은 이미 발견된 디렉토리로의 불필요한 하강을 방지합니다(예를 들어, 이미 project3/.svn을 찾았기 때문에 project3/src를 검색하지 않음). 하지만
형제 디렉토리(project2 및 project3)가 발견되도록 보장합니다.
다른 유용한 예
• 여러 파일 유형을 검색합니다.
$ find /tmp -type f,d,l
디렉토리 /tmp에서 파일, 디렉토리 및 심볼릭 링크를 검색하여 이러한 유형을 쉼표로 구분된 목록(GNU 확장)으로 전달합니다. 이는 더 길지만 더
이식성이 뛰어난 다음 명령과 동일합니다.
$ find /tmp \( -type f -o -type d -o -type l \)
• 특정 이름 needle이 있는 파일을 검색하고 첫 번째 파일을 찾으면 즉시 중지합니다.
$ find / -name needle -print -quit
• 일부 코너 케이스에 대한 -printf 작업의 %f 및 %h 형식 지시문의 해석을 보여줍니다. 다음은 출력을 포함한
예입니다.
$ find . .. / /tmp /tmp/TRACE 컴파일 컴파일/64/테스트/찾기 -최대 깊이 0 -printf '[%h][%f]\n'
[.][.]
[.][..]
[][/]
[][tmp]
[/tmp][추적]
[.][컴파일]
[컴파일/64/테스트][찾기]
종료 상태
find는 모든 파일이 성공적으로 처리되면 상태 0으로 종료되고,
오류가 발생하면 0보다 큰 상태로 종료됩니다. 이는 의도적으로 매우 광범위한 설명이지만 반환 값이 0이 아닌 경우 find의 결과의 정확성에 의존해서는 안 됩니다.
오류가 발생하면 find는 지정된 모든 작업을 완료하지 않고 즉시 중지될 수 있습니다.
예를 들어, 일부 시작점이 검사되지 않았거나
-exec ... {} + 또는 -execdir ... {} + 에 대한 보류 중인 일부 프로그램 호출이 수행되지 않았을 수 있습니다.
이력
findutils-4.2.2부터 파일 이름 패턴에 사용되는 셸 메타문자(예: `*', `?' 또는 `[]')는 IEEE POSIX
해석 126에서 요구하기 때문에 선행 `.'과 일치합니다.
findutils-4.3.3부터 -perm /000은 이제 none 대신 모든 파일과 일치합니다.
나노초 해상도 타임스탬프는 findutils-4.3.3에서 구현되었습니다.
findutils-4.3.11부터 -delete 작업은 실패할 때 find의 종료 상태를 0이 아닌 값으로 설정합니다. 그러나 find는 즉시 종료되지 않습니다.
이전에는 find의 종료 상태가 -delete의 실패에 영향을 받지 않았습니다.
추가된 기능 또한 다음에서 발생
-files0-from 4.9.0
-newerXY 4.3.3 BSD
-D 4.3.1
-O 4.3.1
-readable 4.3.0
-writable 4.3.0
-executable 4.3.0
-regextype 4.2.24
-exec ... + 4.2.12 POSIX
-execdir 4.2.12 BSD
-okdir 4.2.12
-samefile 4.2.11
-H 4.2.5 POSIX
-L 4.2.5 POSIX
-P 4.2.5 BSD
-delete 4.2.3
-quit 4.2.3
-d 4.2.3 BSD
-wholename 4.2.0
-iwholename 4.2.0
-ignore_readdir_race 4.2.0
-fls 4.0
-ilname 3.8
-iname 3.8
-ipath 3.8
-iregex 3.8
-perm +MODE 구문은 findutils-4.5.12에서 제거되었으며, 대신
-perm /MODE가 사용되었습니다. +MODE 구문은 2005년에 출시된 findutils-4.2.21 이후로 더 이상 사용되지 않습니다.
버그가 아닌 것
연산자 우선순위의 놀라움
find . -name afile -o -name bfile -print 명령은 실제로 find . -name afile -o \(
-name bfile -a -print \)와 동일하기 때문에 afile을 인쇄하지 않습니다. -a의 우선순위가 -o보다 높다는 점과 테스트 사이에 연산자가 지정되지 않은 경우 -a가 가정됩니다.
"경로는 표현식 앞에 와야 합니다" 오류 메시지
$ find . -name *.c -print
find: 경로는 표현식 앞에 와야 합니다
find: 술어 `-name' 뒤에 따옴표 없는 패턴이 가능할까요?
이는 셸이 패턴 *.c를 현재 디렉토리에 있는 두 개 이상의 파일 이름으로 확장하고 명령줄에서 결과 파일 이름을 다음과 같이 find에 전달할 때 발생합니다.
find . -name frcode.c Locate.c word_io.c -print
이 명령은 물론 작동하지 않을 것입니다. -name 술어는 인수로 정확히 하나의 패턴만 허용하기 때문입니다. 이런 식으로 하는 대신 패턴을 따옴표로 묶거나 와일드카드를 이스케이프하여 find가 부모 셸에서 확장된 파일 이름 대신 파일 이름 일치를 검색하는 동안 와일드카드와 함께 패턴을 사용할 수 있도록 해야 합니다.
$ find . -name '*.c' -print
$ find . -name \*.c -print
버그
POSIX 표준이 find에 대해 지정하는 동작에는 고유한 보안 문제가 있으므로 수정할 수 없습니다. 예를 들어 -exec 동작은 본질적으로 안전하지 않으므로 -execdir을 대신 사용해야 합니다.
환경 변수 LC_COLLATE는 -ok 동작에 영향을 미치지 않습니다.
버그 보고
GNU findutils 온라인 도움말: <https://www.gnu.org/software/findu‐
tils/#get-help>
번역 버그는 <https://translationproject.org/team/>에 보고하세요.
다른 문제는 GNU Savannah 버그 추적기의 양식을 통해 보고하세요:
<https://savannah.gnu.org/bugs/?group=findutils>
GNU findutils 패키지에 대한 일반적인 주제는
bug-findutils 메일링 리스트에서 논의합니다:
<https://lists.gnu.org/mailman/listinfo/bug-findutils>
저작권
저작권 © 1990-2022 Free Software Foundation, Inc. 라이선스 GPLv3+:
GNU GPL 버전 3 이상 <https://gnu.org/licenses/gpl.html>.
이것은 무료 소프트웨어입니다. 자유롭게 변경하고 재배포할 수 있습니다.
법으로 허용되는 범위 내에서 보증은 없습니다.
또한 참조
chmod(1), Locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2),
ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7)
전체 문서 <https://www.gnu.org/software/findutils/find>
또는 다음을 통해 로컬에서 사용 가능: info find
FIND(1)
형태 : find [옵션] [경로] [검색조건] [동작]
기능 : [경로]에서 [검색조건]에 해당하는 파일을 찾고, [동작]을 실행한다.
[검색조건](man 테스트 참조)
-name pattern : 파일명 검색
-type 타입
-user loginID : 지정한 사용자가 소유한 모든 파일에서 검색
-perm : 지정한 사용 권한과 일치하는 파일을 검색
[동작](man의 표현식 참조)
-exec [명령] {}\ : 검색된 파일에 명령을 실행한다.
-ok [명령] {}\ : 검색된 파일에 사용자의 확인을 받은 뒤 명령을 실행한다.
-print : 검색된 파일의 절대 경로명을 화면에 출력한다.(기본동작, 생략가능)
-ls : 검색 결과를 긴 목록 형식으로 출력한다.
'IT 공부내용 정리 > Linux' 카테고리의 다른 글
| 터미널 명령어 - chmod 파일의 접근 권한을 설정하고 싶을 때 (1) | 2025.03.06 |
|---|---|
| 터미널 명령어 - which / whereis 명령어 파일이 어디 있는지 알고 싶을 때 (0) | 2025.03.06 |
| 터미널 명령어 - grep 파일 내용 중에 찾고 싶은 값이 있다면 (1) | 2025.03.06 |
| 터미널 명령어 - touch 파일의 수정시간을 변경하고 싶을 때 (0) | 2025.03.06 |
| 터미널 명령어 - ln 바로가기를 만들고 싶을 때 (0) | 2025.02.28 |