FIND(1POSIX)
๐ find(1POSIX) โ the POSIX Programmer's Manual, bestie edition
okay so. welcome to find(1POSIX) ๐ this one lives in the POSIX Programmer's Manual, and heads up before we even start:
PROLOG โ this manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. ๐
like. she's a standard, not a promise. check your local Linux page, k? ๐ซถ
โจ NAME โจ
find โ find files ๐ no cap, that's the whole job.
๐ธ SYNOPSIS ๐ธ
find [-H|-L] path... [operand_expression...]
๐ฆ DESCRIPTION ๐ฆ
so find is gonna recursively descend the directory hierarchy from each file you hand it as a path, and for every single file it bumps into, it evaluates a Boolean expression built out of the primaries in the OPERANDS section. yes, a whole expression. she's doing math. ๐
here's the vibe on how paths get constructed, and this part is exact so pay attention bestie:
- Each
pathoperand shall be evaluated unaltered as it was provided, including all trailing<slash>characters. - All pathnames for other files encountered in the hierarchy shall consist of the concatenation of the current
pathoperand, a<slash>if the currentpathoperand did not end in one, and the filename relative to thepathoperand. - That relative portion shall contain no dot or dot-dot components, no trailing
<slash>characters, and only single<slash>characters between pathname components. โจ
also, she goes deep. like, arbitrary depths deep:
- The
findutility shall be able to descend to arbitrary depths in a file hierarchy and shall not fail due to path length limitations โ unless apathoperand specified by the application exceeds{PATH_MAX}requirements. ๐ณ๏ธ
and she catches the loops, thank god, because otherwise we'd be here forever:
- The
findutility 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,
findshall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. ๐
and finally, the chaotic one:
- If a file is removed from or added to the directory hierarchy being searched, it is unspecified whether or not
findincludes that file in its search. it's giving "don't touch the filesystem while she's working." ๐ญ
๐ OPTIONS ๐
The find utility shall conform to the Base Definitions volume of POSIX.1โ2017, Section 12.2, Utility Syntax Guidelines. (yes she's polite, she follows the rules ๐)
The following options shall be supported by the implementation:
-Hโ Cause the file information and file type evaluated for each symbolic link encountered as apathoperand on the command line to be those of the file referenced by the link, and not the link itself. If the referenced file does not exist, the file information and type shall be for the link itself. File information and type for symbolic links encountered during the traversal of a file hierarchy shall be that of the link itself. so like, command line links get dereferenced, traversal links do not. iykyk. ๐ช-Lโ Cause the file information and file type evaluated for each symbolic link encountered as apathoperand on the command line or encountered during the traversal of a file hierarchy to be those of the file referenced by the link, and not the link itself. If the referenced file does not exist, the file information and type shall be for the link itself. she's-Hbut with main character energy โ she dereferences everywhere. ๐
okay and now the plot twist:
- Specifying more than one of the mutually-exclusive options
-Hand-Lshall not be considered an error. The last option specified shall determine the behavior of the utility. โจ - If neither
-Hnor-Lis specified, then the file information and type for symbolic links encountered as apathoperand on the command line or encountered during the traversal of a file hierarchy shall be that of the link itself.
๐ OPERANDS ๐
The following operands shall be supported:
The first operand and subsequent operands up to but not including the first operand that starts with a '-', or is a '!' or a '(', shall be interpreted as path operands. If the first operand starts with a '-', or is a '!' or a '(', the behavior is unspecified. Each path operand is a pathname of a starting point in the file hierarchy. ๐ฑ
The first operand that starts with a '-', or is a '!' or a '(', and all subsequent arguments shall be interpreted as an expression made up of the following primaries and operators.
In the descriptions, wherever n is used as a primary argument, it shall be interpreted as a decimal integer optionally preceded by a <plus-sign> ('+') or <hyphen-minus> ('-'), as follows:
+nโ More than n. ๐nโ Exactly n. ๐ฏ-nโ Less than n. ๐
The following primaries shall be supported:
-namepattern โ The primary shall evaluate as true if the basename of the current pathname matches pattern using the pattern matching notation described in Section 2.13, Pattern Matching Notation. The additional rules in Section 2.13.3, Patterns Used for Filename Expansion do not apply โ as this is a matching operation, not an expansion. okay so no, your shell is not doing the expanding here, she's doing it herself. ๐ง-pathpattern โ The primary shall evaluate as true if the current pathname matches pattern using the pattern matching notation described in Section 2.13, Pattern Matching Notation. The additional rules in Section 2.13.3, Patterns Used for Filename Expansion do not apply โ as this is a matching operation, not an expansion. same deal, whole path this time. ๐-nouserโ The primary shall evaluate as true if the file belongs to a user ID for which thegetpwuid()function defined in the System Interfaces volume of POSIX.1โ2017 (or equivalent) returnsNULL. ghost user. ๐ป-nogroupโ The primary shall evaluate as true if the file belongs to a group ID for which thegetgrgid()function defined in the System Interfaces volume of POSIX.1โ2017 (or equivalent) returnsNULL. ghost group. ๐ป-xdevโ The primary shall always evaluate as true; it shall causefindnot to continue descending past directories that have a different device ID (st_dev, see thestat()function defined in the System Interfaces volume of POSIX.1โ2017). If any-xdevprimary is specified, it shall apply to the entire expression even if the-xdevprimary would not normally be evaluated. she sees one-xdevand the whole expression respects it. periodt. ๐-pruneโ The primary shall always evaluate as true; it shall causefindnot to descend the current pathname if it is a directory. If the-depthprimary is specified, the-pruneprimary shall have no effect. โ๏ธ-perm [-]modeโ The mode argument is used to represent file mode bits. It shall be identical in format to thesymbolic_modeoperand described inchmod, and shall be interpreted as follows. To start, a template shall be assumed with all file mode bits cleared. An op symbol of'+'shall set the appropriate mode bits in the template;'-'shall clear the appropriate bits;'='shall set the appropriate mode bits, without regard to the contents of the file mode creation mask of the process. The op symbol of'-'cannot be the first character of mode โ this avoids ambiguity with the optional leading<hyphen-minus>. Since the initial mode is all bits off, there are not any symbolic modes that need to use'-'as the first character. ๐- If the
<hyphen-minus>is omitted, the primary shall evaluate as true when the file permission bits exactly match the value of the resulting template. - Otherwise, if mode is prefixed by a
<hyphen-minus>, the primary shall evaluate as true if at least all the bits in the resulting template are set in the file permission bits.
- If the
-perm [-]onumโ If the<hyphen-minus>is omitted, the primary shall evaluate as true when the file mode bits exactly match the value of the octal number onum (see the description of the octal mode inchmod). Otherwise, if onum is prefixed by a<hyphen-minus>, the primary shall evaluate as true if at least all of the bits specified in onum are set. In both cases, the behavior is unspecified when onum exceeds07777. โ ๏ธ-typec โ The primary shall evaluate as true if the type of the file is c, where c is'b','c','d','l','p','f', or's'for block special file, character special file, directory, symbolic link, FIFO, regular file, or socket, respectively. the whole squad:bcdlpfs. ๐ซถ-linksn โ The primary shall evaluate as true if the file has n links. ๐-useruname โ The primary shall evaluate as true if the file belongs to the user uname. If uname is a decimal integer and thegetpwnam()(or equivalent) function does not return a valid user name, uname shall be interpreted as a user ID. ๐ง๐ป-groupgname โ The primary shall evaluate as true if the file belongs to the group gname. If gname is a decimal integer and thegetgrnam()(or equivalent) function does not return a valid group name, gname shall be interpreted as a group ID. ๐ฅ-sizen[c]โ The primary shall evaluate as true if the file size in bytes, divided by 512 and rounded up to the next integer, is n. If n is followed by the character'c', the size shall be in bytes. ๐-atimen โ The primary shall evaluate as true if the file access time subtracted from the initialization time, divided by86400(with any remainder discarded), is n. โฐ-ctimen โ The primary shall evaluate as true if the time of last change of file status information subtracted from the initialization time, divided by86400(with any remainder discarded), is n. โฐ-mtimen โ The primary shall evaluate as true if the file modification time subtracted from the initialization time, divided by86400(with any remainder discarded), is n. โฐ-executility_name[argument ...];-executility_name[argument ...]{}+โ The end of the primary expression shall be punctuated by a<semicolon>or by a<plus-sign>. Only a<plus-sign>that immediately follows an argument containing only the two characters"{}"shall punctuate the end of the primary expression. Other uses of the<plus-sign>shall not be treated as special. ๐จ
If the primary expression is punctuated by a <semicolon>, the utility utility_name shall be invoked once for each pathname and the primary shall evaluate as true if the utility returns a zero value as exit status. A utility_name or argument containing only the two characters "{}" shall be replaced by the current pathname. If a utility_name or argument string contains the two characters "{}", but not just the two characters "{}", it is implementation-defined whether find replaces those two characters or uses the string without change. ๐
to be continued, bestie โ she's long and she knows it ๐
okay so if that primary expression ends with a <plus-sign>? bestie, it always evaluates as true, and the pathnames it gets evaluated for get aggregated into sets. The utility_name gets invoked once per set of aggregated pathnames. Each invocation starts after the last pathname in the set is aggregated, and has to be done before find exits and before the first pathname of the next set (if there is one) gets aggregated for this primary โ but other than that, it's unspecified whether the invocation happens before, during, or after the evaluations of the other primaries ๐. If any invocation returns a non-zero exit status, find returns a non-zero exit status too. An argument containing only the two characters "{}" gets replaced by the set of aggregated pathnames, with each pathname passed as a separate argument to the invoked utility, in the same order it was aggregated. The size of any set of two or more pathnames is limited so that running the utility doesn't blow past the system's {ARG_MAX} limit ๐. And if you've got more than one argument containing "{}", the behavior is unspecified โ no cap.
The current directory for the invocation of utility_name is the same as the current directory when find was started. If utility_name names any of the special built-in utilities (see Section 2.14, Special Built-In Utilities), the results are undefined. ๐
-ok utility_name [argument ...] ;โ this one's basically-exec's twin, except that using a <plus-sign> to punctuate the end of the primary expression need not be supported, andfindasks you to confirm the invocation ofutility_name(using the current file as an argument) by writing to standard error, exactly like the STDERR section says. If your response on standard input is affirmative, the utility gets invoked. Otherwise, the command is not invoked and the value of the-okoperand is false. ๐-printโ always true, always slaying; it makes the current pathname get written to standard output. โจ-newer fileโ true if the modification time of the current file is more recent than the modification time of the file named by the pathname file.-depthโ always evaluates as true; it makes descent of the directory hierarchy happen so that all entries in a directory are acted on before the directory itself. If no-depthprimary is specified, all entries in a directory are acted on after the directory itself. And if any-depthprimary is specified, it applies to the entire expression โ even if that-depthprimary wouldn't normally get evaluated. iconic behavior honestly ๐
๐ Combining them: the OPERATORS ๐
The primaries can be combined with these operators, listed in order of decreasing precedence:
( expression )โ true if expression is true.! expressionโ negation of a primary; the unary NOT operator.expression [-a] expressionโ conjunction of primaries; the AND operator is implied when you just put two primaries next to each other, or made explicit with the optional-aoperator. The second expression is not evaluated if the first one is false.expression -o expressionโ alternation of primaries; the OR operator. The second expression is not evaluated if the first one is true.
If no expression is present at all, -print is used as the expression. Otherwise, if your given expression doesn't contain any of the primaries -exec, -ok, or -print, then the given expression is effectively replaced by:
( given_expression ) -print
The -user, -group, and -newer primaries each evaluate their respective arguments only once. periodt.
โ ๏ธ Heads up: when the file type evaluated for the current file is a symbolic link, the results of evaluating the -perm primary are implementation-defined. Not our problem, not our rules. ๐คทโโ๏ธ
๐ STDIN ๐
If the -ok primary is used, the response gets read from standard input. An entire line is read as the response. Otherwise, standard input is not used. that's it that's the section ๐ซถ
๐ธ INPUT FILES ๐ธ
None. literally none. nothing to see here bestie โจ
๐ฆ ENVIRONMENT VARIABLES ๐ฆ
These variables affect how find runs, so let's get into it:
LANGโ provides a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of POSIX.1โ2017, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)LC_ALLโ if set to a non-empty string value, it overrides the values of all the other internationalization variables. ๐LC_COLLATEโ determines the locale for the behavior of ranges, equivalence classes, and multi-character collating elements used in the pattern matching notation for the-noption, and in the extended regular expression defined for theyesexprlocale keyword in theLC_MESSAGEScategory.LC_CTYPEโ determines the locale for interpreting sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments), the behavior of character classes within the pattern matching notation used for the-noption, and the behavior of character classes within regular expressions used in the extended regular expression defined for theyesexprlocale keyword in theLC_MESSAGEScategory.LC_MESSAGESโ determines the locale used to process affirmative responses, and the locale used to affect the format and contents of diagnostic messages and prompts written to standard error.NLSPATHโ determines the location of message catalogs for the processing ofLC_MESSAGES.PATHโ determines the location of theutility_namefor the-execand-okprimaries, as described in the Base Definitions volume of POSIX.1โ2017, Chapter 8, Environment Variables.
โญ ASYNCHRONOUS EVENTS โญ
Default. keep it simple bestie ๐
โจ STDOUT โจ
The -print primary makes the current pathnames get written to standard output. The format shall be:
"%s\n", <path>
๐ STDERR ๐
The -ok primary writes a prompt to standard error containing at least the utility_name to be invoked and the current pathname. In the POSIX locale, the last non-<blank> in the prompt shall be '?'. The exact format used is unspecified. Otherwise, standard error is used only for diagnostic messages.
๐ OUTPUT FILES ๐
None. again. we love a low-maintenance page ๐
๐ EXTENDED DESCRIPTION ๐
None. (yes really, that's the whole thing ๐ญ)
๐ EXIT STATUS ๐
The following exit values shall be returned:
0โ all path operands were traversed successfully. slay ๐>0โ an error occurred. ๐
๐ง CONSEQUENCES OF ERRORS ๐ง
Default.
The following sections are informative.
๐ APPLICATION USAGE ๐
When used in operands, pattern matching notation, <semicolon>, <left-parenthesis>, and <right-parenthesis> characters are special to the shell and must be quoted (see Section 2.2, Quoting). fr fr, don't forget this one, your shell will eat them otherwise ๐ญ
The bit that's traditionally used for sticky (historically 01000) is specified in the -perm primary using the octal number argument form. Since this bit is not defined by this volume of POSIX.1โ2017, applications must not assume that it actually refers to the traditional sticky bit. noted bestie, no assumptions allowed ๐ซถ
โจ EXAMPLES โจ
okay bestie, let's get into the actual receipts ๐งพ
- these two commands are literally the same thing:
find .
find . -print
They both write out the entire directory hierarchy from the current directory. same energy, same output, no cap.
- The following command:
find / \( -name tmp -o -name '*.xx' \) -atime +7 -exec rm {} \;
removes all files named tmp or ending in .xx that have not been accessed for seven or more 24-hour periods. so it's giving cleanup era, but make sure you meant it.
- The following command:
find . -perm -o+w,+s
prints (-print is assumed) the names of all files in or below the current directory, with all of the file permission bits S_ISUID, S_ISGID, and S_IWOTH set. permission bits popping off fr fr.
- The following command:
find . -name SCCS -prune -o -print
recursively prints pathnames of all files in the current directory and below, but skips directories named SCCS and files in them. we do not see SCCS, it is not invited to the function.
- The following command:
find . -print -name SCCS -prune
behaves as in the previous example, but prints the names of the SCCS directories. so now we're naming names, iconic.
- The following command is roughly equivalent to the
-ntextension totest:
if [ -n "$(find file1 -prune -newer file2)" ]; then
printf %s\\n "file1 is newer than file2"
fi
comparison but make it find-coded.
- The descriptions of
-atime,-ctime, and-mtimeuse the terminology n โ86400 second periods (days)โ. For example, a file accessed at 23:59 is selected by:
find . -atime -1 -print
at 00:01 the next day (less than 24 hours later, not more than one day ago); the midnight boundary between days has no effect on the 24-hour calculation. math is math, bestie.
- The following command:
find . ! -name . -prune -name '*.old' -exec \
sh -c 'mv "$@" ../old/' sh {} +
performs the same task as:
mv ./*.old ./.old ./.*.old ../old/
while avoiding an โArgument list too longโ error if there are a large number of files ending with .old and without running mv if there are no such files (and avoiding โNo such file or directoryโ errors if ./.old does not exist or no files match ./*.old or ./.*.old).
The alternative:
find . ! -name . -prune -name '*.old' -exec mv {} ../old/ \;
is less efficient if there are many files to move because it executes one mv command per file. one per file? girl, that's a lot of spawning.
- On systems configured to mount removable media on directories under
/media, the following command searches the file hierarchy for files larger than 100000 KB without searching any mounted removable media:
find / -path /media -prune -o -size +200000 -print
skip the media, find the big files, slay.
- Except for the root directory, and
"//"on implementations where"//"does not refer to the root directory, no pattern given to-namewill match a<slash>, because trailing<slash>characters are ignored when computing the basename of the file under evaluation. Given two empty directories namedfooandbar, the following command:
find foo/// bar/// -name foo -o -name 'bar?*'
prints only the line "foo///". the slashes said bye and the match said no. ๐
๐ง RATIONALE ๐ง
okay so the -a operator was retained as an optional operator for compatibility with historical shell scripts, even though it is redundant with expression concatenation. it's giving legacy support, bestie.
The descriptions of the '-' modifier on the mode and onum arguments to the -perm primary agree with historical practice on BSD and System V implementations. System V and BSD documentation both describe it in terms of checking additional bits; in fact, it uses the same bits, but checks for having at least all of the matching bits set instead of having exactly the matching bits set.
The exact format of the interactive prompts is unspecified. Only the general nature of the contents of prompts are specified because:
- Implementations may desire more descriptive prompts than those used on historical implementations.
- Since the historical prompt strings do not terminate with
<newline>characters, there is no portable way for another program to interact with the prompts of this utility via pipes.
Therefore, an application using this prompting option relies on the system to provide the most suitable dialog directly with the user, based on the general guidelines specified. so like, the vibe of the prompt is specified, not the exact text. noted.
The -name file operand was changed to use the shell pattern matching notation so that find is consistent with other utilities using pattern matching. consistency is the moment.
The -size operand refers to the size of a file, rather than the number of blocks it may occupy in the file system. The intent is that the st_size field defined in the System Interfaces volume of POSIX.1โ2017 should be used, not the st_blocks found in historical implementations. There are at least two reasons for this:
- In both System V and BSD,
findonly usesst_sizein size calculations for the operands specified by this volume of POSIX.1โ2017. (BSD usesst_blocksonly when processing the-lsprimary.) - Users usually think of file size in terms of bytes, which is also the unit used by the
lsutility for the output from the-loption. (In both System V and BSD,lsusesst_sizefor the-loption size field and usesst_blocksfor thels -scalculations. This volume of POSIX.1โ2017 does not specifyls -s.)
bytes are the people's unit, honestly.
The descriptions of -atime, -ctime, and -mtime were changed from the SVID description of n โdaysโ to n being the result of the integer division of the time difference in seconds by 86400. The description is also different in terms of the exact timeframe for the n case (versus the +n or -n), but it matches all known historical implementations. It refers to one 86400 second period in the past, not any time from the beginning of that period to the current time. For example, -atime 2 is true if the file was accessed any time in the period from 72 hours to 48 hours ago. time math but make it exact.
Historical implementations do not modify "{}" when it appears as a substring of an -exec or -ok utility_name or argument string. There have been numerous user requests for this extension, so this volume of POSIX.1โ2017 allows the desired behavior. At least one recent implementation does support this feature, but encountered several problems in managing memory allocation and dealing with multiple occurrences of "{}" in a string while it was being developed, so it is not yet required behavior. so close to being required, but the memory management said not today.
Assuming the presence of -print was added to correct a historical pitfall that plagues novice users, it is entirely upwards-compatible from the historical System V find utility. In its simplest form (find directory), it could be confused with the historical BSD fast find. The BSD developers agreed that adding -print as a default expression was the correct decision and have added the fast find functionality within a new utility called locate. plot twist: the default print was a glow-up.
Historically, the -L option was implemented using the primary -follow. The -H and -L options were added for two reasons. First, they offer a finer granularity of control and consistency with other programs that walk file hierarchies. Second, the -follow primary always evaluated to true. As they were historically really global variables that took effect before the traversal began, some valid expressions had unexpected results. An example is the expression -print -o -follow. Because -print always evaluates to true, the standard order of evaluation implies that -follow would never be evaluated. This was never the case. Historical practice for the -follow primary, however, is not consistent. Some implementations always follow symbolic links on the command line whether -follow is specified or not. Others follow symbolic links on the command line only if -follow is specified. Both behaviors are provided by the -H and -L options, but scripts using the current -follow primary would be broken if the -follow option is specified to work either way. global state before traversal? chaotic. we love a fixed option.
Since the -L option resolves all symbolic links and the -type l primary is true for symbolic links that still exist after symbolic links have been resolved, the command:
find -L . -type l
prints a list of symbolic links reachable from the current directory that do not resolve to accessible files. broken links found, no cap.
A feature of SVR4's find utility was the -exec primary's + terminator. This allowed filenames containing special characters (especially <newline> characters) to be grouped together without the problems that occur if such filenames are piped to xargs. Other implementations have added other ways to get around this problem, notably a -print0 primary that wrote filenames with a null byte terminator. This was considered here, but not adopted. Using a null terminator meant that any utility that was going to process find's -print0 output had to add a new option to parse the null terminators it would now be reading. the null byte idea was in the group chat and then left on read.
The "-exec...{}+" syntax adopted was a result of IEEE PASC Interpretation 1003.2 #210. It should be noted that this is an incompatible change to IEEE Std 1003.2โ1992. For example, the following command printed all files with a - after their name if they are regular files, and a + otherwise:
find / -type f -exec echo {} - ';' -o -exec echo {} + ';'
The change invalidates usage like this. Even though the previous standard stated that this usage would work, in practice many did not support it and the standard developers felt it better to now state that this was not allowable. so that old usage is cancelled, bestie. periodt.
๐ฎ FUTURE DIRECTIONS ๐ฎ
None. that's it, nothing on the horizon.
๐ SEE ALSO ๐
- Section 2.2, Quoting
- Section 2.13, Pattern Matching Notation
- Section 2.14, Special Built-In Utilities
chmod,mv,pax,sh,test- The Base Definitions volume of POSIX.1โ2017, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines
- The System Interfaces volume of POSIX.1โ2017,
fstatat(),getgrgid(),getpwuid()
๐ COPYRIGHT ๐
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
and that's the whole vibe, bestie! source/version/date: IEEE/The Open Group, 2017, FIND(1POSIX). ๐โจ
๐ฆ where this page comes from
- debian bookworm: manpages-posix 2017a-2 ยท Other
- debian trixie: manpages-posix 2017a-2 ยท Other
- ubuntu jammy: manpages-posix 2017a-2 ยท Other
- ubuntu noble: manpages-posix 2017a-2 ยท Other
- ubuntu resolute: manpages-posix 2017a-2build1 ยท Other
- ubuntu stonking: manpages-posix 2017a-2.1 ยท Other
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms