FIND(1)
โจ find(1) โ General Commands Manual โจ ๐
okay bestie, welcome to the GNU find page. It's giving search the whole directory tree energy, and we're doing it in ten parts, so hydrate and buckle up. ๐ซถ
๐ธ NAME ๐ธ
find โ search for files in a directory hierarchy. That's it, that's the name. Iconic, lowkey. ๐
โจ SYNOPSIS โจ
find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...]
[expression]
๐ DESCRIPTION ๐
This manual page is documenting the GNU version of find, no cap. So what does GNU find actually do? It searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, following the rules of precedence (go peek at the OPERATORS section for those). It keeps going until the outcome is known โ and bestie, that means the left hand side is false for and operations, true for or โ and at that point find moves on to the next file name. If no starting-point is specified, `.' is assumed. Periodt. ๐
If you're usingfindsomewhere where security is important โ like, for example, if you're using it to search directories that are writable by other users โ you should read the`Security Considerations'chapter of the findutils documentation. That chapter is called Finding Files and it comes withfindutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. Fr fr, go read it if that's your situation. ๐ซถ
โจ OPTIONS โจ
ok bestie, buckle up, this is the part where find decides how it feels about symlinks ๐
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, if the output is going to be read by another program โ trust, fr fr ๐ซถ).
This manual page talks about options within the expression list. These options control the behaviour of find but are specified immediately 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 arguments 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 dubious path names with either ./ or to use absolute path names starting with /. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. ๐
-Pโ Never follow symbolic links. This is the default behaviour. Whenfindexamines 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. it's giving "i am what i am" energy ๐ช-Lโ Follow symbolic links. Whenfindexamines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link orfindis unable to examine the file to which the link points). Use of this option implies-noleaf. If you later use the-Poption,-noleafwill still be in effect. If-Lis in effect andfinddiscovers a symbolic link to a subdirectory during its search, the subdirectory 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 broken). 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 command line arguments. Whenfindexamines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic 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 symbolic link cannot be examined. If-His 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 0would prevent this).
If more than one of -H, -L and -P is specified, each overrides the others; 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 unless either -H or -L is specified. last one wins, periodt โจ
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 consideration 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). it's lowkey positional bestie, so order matters ๐
-Ddebugopts โ Print diagnostic information; this can be helpful to diagnose problems with whyfindis 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 offind -D help. Valid debug options include:execโ Show diagnostic information relating to-exec,-execdir,-okand-okdiroptโ Prints diagnostic information relating to the optimisation of the expression tree; see the-Ooption.ratesโ Prints a summary indicating how often each predicate succeeded or failed.searchโ Navigate the directory tree verbosely.statโ Print messages as files are examined with thestatandlstatsystem calls. Thefindprogram tries to minimise such calls.treeโ Show the expression tree in its original and optimized form.allโ Enable all of the other debug options (buthelp).helpโ Explain the debugging options.
-Olevelโ Enables query optimisation. Thefindprogram 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-nameand-regex) are performed first.2โ Any-typeor-xtypetests 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 byreaddir()and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the-fstype FOOpredicate and specify a filesystem typeFOOwhich is not known (that is, present in/etc/mtab) at the timefindstarts, that predicate is equivalent to-false.3โ At this optimisation level, the full cost-based query optimizer 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 evaluated earlier, and for-a, predicates which are likely to fail are evaluated earlier.
The cost-based optimizer 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 optimizer 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, robust 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 optimisation level and ensures that the result is the same. ๐
โ ๏ธ bestie the re-ordering of operations performed by the cost-based optimizer can result in user-visible behaviour change. For example, the-readableand-emptypredicates are sensitive to re-ordering. If they are run in the order-empty -readable, an error message will be issued for unreadable directories. If they are run in the order-readable -emptyno error message will be issued. This is the reason why such operation re-ordering is not performed at the default optimisation level. ๐
๐ EXPRESSION ๐
ok so 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 expression 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
-emptytest for example 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
-printaction for example prints the name of the current file on the standard output. ๐จ๏ธ
๐ Global options ๐
Okay so bestie, global options are the ones that affect the operation of tests and actions specified on any part of the command line. Like, anywhere. They're always true โ every single one, no cap. The -depth option for example makes find traverse the file system in a depth-first order. ๐ซ
๐ Positional options ๐
Positional options are the picky ones โ they affect only the tests or actions that come after them. They also always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. iykyk โจ
๐งฎ 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. slay ๐
The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -fls, -fprint, -fprint0, -fprintf, -ls, -ok, -okdir, -print0, -printf and -print. ๐
The -delete action also acts like an option (since it implies -depth). Sneaky iconic behaviour fr fr.
๐ POSITIONAL OPTIONS ๐
Positional options always return true. They affect only tests occurring later on the command line. No take-backs, no retroactive vibes. ๐ฆ
-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-Loption instead. Dereference symbolic links. Implies-noleaf. The-followoption affects only those tests which appear after it on the command line. Unless the-Hor-Loption has been specified, the position of the-followoption changes the behaviour of the-newerpredicate; any files listed as the argument of-newerwill be dereferenced if they are symbolic links. The same consideration applies to-newerXY,-anewerand-cnewer. Similarly, the-typepredicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using-followcauses the-lnameand-ilnamepredicates always to return false. ๐ญ
Ngl,-followis giving deprecated. Just use-L, bestie.
-regextype typeโ Changes the regular expression syntax understood by-regexand-iregextests 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. If you do not use this option,findbehaves as if the regular expression typeemacshad been specified. ๐ค-warn,-nowarnโ Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions thatfindmight encounter when it searches directories. The default behaviour corresponds to-warnif standard input is a tty, and to-nowarnotherwise. If a warning message relating to command-line usage is produced, the exit status offindis not affected. If thePOSIXLY_CORRECTenvironment variable is set, and-warnis also used, it is not specified which, if any, warnings will be active. ๐
๐ GLOBAL OPTIONS ๐
Global options always return true. Global options take effect even for tests which occur earlier on the command line โ main character energy, they don't care about your ordering. To prevent confusion, global options should be 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. Different category, different vibe. ๐
-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-deleteaction 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 passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points tofind.
Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. Pick a lane. ๐ซ
The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. ๐
The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non-Zero exit code later. ๐
In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. ๐ธ
The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. ๐ซถ
Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. ๐ญ (unspecified is giving "we literally cannot promise you anything", and honestly? valid.)
-help,--helpโ Print a summary of the command-line usage offindand exit. ๐-ignore_readdir_raceโ Normally,findwill emit an error message when it fails to stat a file. If you give this option and a file is deleted between the timefindreads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. 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 twofindcommands instead, one with the option and one without it). ๐โ๏ธ
Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. โจ
-maxdepth levelsโ Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using-maxdepth 0means 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 1means process all files except the starting-points. ๐ณ๏ธ-mountโ Ignore files on other devices. ๐ง-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'.'entry. Additionally, its subdirectories (if any) each have a'..'entry linked to that directory. Whenfindis examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories ('leaf'files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. ๐-version,--versionโ Print thefindversion number and exit. ๐ท๏ธ-xdevโ Don't descend into directories on other devices. ๐
๐ TESTS ๐
Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation 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 error 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โ Like-newer, but test if the time of the last access of the current file is more recent than that of the last data modification of the reference file. In other words, this test is equivalent to-neweram. Fails if the timestamps are equal. If reference is a symbolic link and the-Hoption or the-Loption is in effect, then the time of the last data modification of the file it points to is always used. ๐ฐ๏ธ-atime nโ bestie, this one is asking: was this file last accessed less than, more than, or exactlyn*24hours ago? โฐ And here's the tea โ whenfinddoes the math on how many 24-hour periods have passed, it straight up ignores any fractional part, no cap. So if you wanna match-atime +1, your file has to have been accessed at least two days ago. The rounding is giving "close enough is not a thing here". ๐-cmin nโ was this file's status last changed less than, more than, or exactlynminutes ago? ๐-cnewer referenceโ okay so this is like-newer, but it tests whether the time of the last status change of the file you're looking at is more recent than the last data modification of the reference file. In other words, it's literally equivalent to-newercm. It fails if the timestamps are equal. ๐ค And ifreferenceis a symbolic link and either the-Hoption or the-Loption is in effect, then the time of the last data modification of the file it points to is always used.-ctime nโ file's status was last changed less than, more than, or exactlyn*24hours ago. Peep the comments under-atimefor how rounding messes with your interpretation of file status change times. ๐-emptyโ file is empty AND it's either a regular file or a directory. That's it, that's the whole vibe. ๐ซ-executableโ matches files that are executable and directories that are searchable (in a file-name-resolution sense) by the current user. This one takes into account access control lists and other permissions artefacts that the-permtest just ignores, periodt. It uses theaccess(2)system call, which means it can be fooled by NFS servers doing UID mapping (or root-squashing) โ because lots of systems implementaccess(2)in the client's kernel and therefore can't use the UID mapping info the server's holding. And since this test is based only on whataccess(2)says, there's no guarantee that a file passing this test can actually be executed. ๐-falseโ always false. That's it. Iconic honestly. ๐-fstype typeโ file is on a filesystem of typetype. Valid filesystem types vary between Unix versions, so here's an incomplete list of ones accepted on some version of Unix or another:ufs,4.2,4.3,nfs,tmp,mfs,S51K,S52K. You can use-printfwith the%Fdirective to see the types of your filesystems. ๐-gid nโ file's numeric group ID is less than, more than, or exactlyn.-group gnameโ file belongs to groupgname(a numeric group ID is allowed too, no judgement).-ilname patternโ like-lname, but the match is case insensitive. If the-Loption or the-followoption is in effect, this test returns false unless the symbolic link is broken. ๐ฆ-iname patternโ like-name, but case insensitive. For example, the patternsfo*andF??match the file namesFoo,FOO,foo,fOo, etc. And the pattern*foo*will also match a file called.foobar. โจ-inum nโ file has an inode number smaller than, greater than, or exactlyn. Honestly it's normally easier to just use the-samefiletest 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, so like, choose wisely. ๐-links nโ file has less than, more than, or exactlynhard links.-lname patternโ file is a symbolic link whose contents match the shell patternpattern. The metacharacters do not treat/or.specially. If the-Loption or the-followoption is in effect, this test returns false unless the symbolic link is broken. ๐-mmin nโ file's data was last modified less than, more than, or exactlynminutes ago.-mtime nโ file's data was last modified less than, more than, or exactlyn*24hours ago. Again, check the comments under-atimefor how rounding affects the interpretation of file modification times. It's the same rounding drama, different timestamp. ๐ญ-name patternโ the base of the file name (that's the path with the leading directories removed) matches the shell patternpattern. Because those leading directories get stripped, your pattern should not include a slash โ-name a/bwill never match anything (and you probably want-pathinstead). The one exception is when your pattern is just a slash (-name /), because that's a valid string for matching the root directory"/"(since the base name of"/"is"/"). ๐ A warning gets issued if a-namepattern can never match โ unless the environment variablePOSIXLY_CORRECTis set or the option-nowarnis used. To ignore a directory and everything under it, use-pruneinstead of checking every single file in the tree; there's an example in the description of that action. Braces are not recognised as special, even though some shells (looking at you, Bash) give braces a special meaning in shell patterns. The filename matching is done with thefnmatch(3)library function. And don't forget to wrap that pattern in quotes to protect it from the shell, bestie. ๐ซถ-newer referenceโ succeeds if the time of the last data modification of the current file is more recent than that of the last data modification of thereferencefile. In other words, it's equivalent to-newermm, though only-neweris in the POSIX standard. It fails if the timestamps are equal. Ifreferenceis a symbolic link and the-Hoption or the-Loption is in effect, then the time of the last data modification of the file it points to is always used. โญ-newerXY referenceโ succeeds if timestampXof the file being considered is newer than timestampYof the filereference. Fails if the timestamps are equal. The lettersXandYcan be any of these:aโ the access time of the file referenceBโ the birth time of the file referencecโ the inode status change time ofreferencemโ the modification time of the file referencetโreferenceis interpreted directly as a time
Some combinations are invalid โ for example, it's invalid for X to be t. Some combinations aren't implemented on all systems; for example B isn't supported everywhere. If you specify an invalid or unsupported combination of XY, you get a fatal error. Time specifications are interpreted the same way as the argument to the -d option of GNU date. And if you try to use the birth time of a reference file and that birth time can't be determined, you get a fatal error message. Also, if you specify a test referring to the birth time of files being examined, that test will fail for any files where the birth time is unknown. ๐
-nogroupโ no group corresponds to the file's numeric group ID. Orphaned group energy. ๐-nouserโ no user corresponds to the file's numeric user ID.-path patternโ the file name matches the shell patternpattern. 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 โ which means this command will never match anything:
find bar -path /foo/bar/myfile -print
find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since that concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except maybe a start point specified on the command line). The -path predicate is also supported by HP-UX find and is part of the POSIX 2008 standard. ๐
-perm modeโ file's permission bits are exactlymode(octal or symbolic). Since an exact match is required, if you want to use this form with symbolic modes you might have to specify a genuinely complex mode string. For example,-perm g=wwill only match files which have mode0020(that is, ones where group write permission is the only permission set). It's way more likely you'll want the/or-forms โ for example-perm -g=w, which matches any file with group write permission. Peep the EXAMPLES section for some illustrative examples. ๐-perm -modeโ all of the permission bitsmodeare set for the file. Symbolic modes are accepted in this form, and this is usually the way you'd want to use them. You must specifyu,g, oroif you use a symbolic mode. EXAMPLES section, go look. ๐ธ-perm /modeโ any of the permission bitsmodeare set for the file. Symbolic modes are accepted here too, and again you must specifyu,g, oroif you use a symbolic mode. EXAMPLES section, bestie. And if no permission bits inmodeare set, this test matches any file โ the idea being to stay consistent with the behaviour of-perm -000. ๐คฏ-perm +modeโ this is no longer supported (and has been deprecated since 2005). Use-perm /modeinstead. Don't do it. Periodt. ๐ซ-readableโ matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts that the-permtest ignores. It uses theaccess(2)system call, so it can be fooled by NFS servers doing UID mapping (or root-squashing), since many systems implementaccess(2)in the client's kernel and therefore can't use the UID mapping information held on the server. ๐ง-regex patternโ the file name matches the regular expressionpattern. 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 notf.*r3. The regular expressions understood byfindare Emacs Regular Expressions by default, but you can change that with the-regextypeoption. โจ-samefilename โ the file points at the same inode as name, like literal twins ๐ฏ. When-Lis in effect, this can include symbolic links too.-sizen[cwbkMG]โ the file uses less than, more than, or exactly n units of space, with the size rounded up. Here are the suffixes you can slap on:bโ for 512-byte blocks (this is the default when you don't use any suffix at all)cโ for byteswโ for two-byte wordskโ 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)
So the size is just the st_size member of the struct stat that the lstat (or stat) system call filled in, rounded up like we said above. In other words, it's consistent with what you get from ls -l, no cap. But bestie, bear in mind that the %k and %b format specifiers of -printf handle sparse files differently. And the b suffix always denotes 512-byte blocks and never 1024-byte blocks, which is not how -ls does things.
The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. IMPORTANT: remember that the size gets 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. That's it, that's the whole vibe. โจ-typec โ the file is of type c:bโ block (buffered) specialcโ character (unbuffered) specialdโ directorypโ named pipe (FIFO)fโ regular filelโ symbolic link; this is never true if the-Loption or the-followoption is in effect, unless the symbolic link is broken. If you wanna search for symbolic links while-Lis in effect, use-xtypeinstead, iykyk.sโ socketDโ door (Solaris)
Wanna search for more than one type at once? Just supply the combined list of type letters separated by a comma , (GNU extension, slay).
-uidn โ the file's numeric user ID is less than, more than, or exactly n.-usedn โ the file was last accessed less than, more than, or exactly n days after its status was last changed.-useruname โ the file is owned by user uname (numeric user ID is allowed too).-wholenamepattern โ see-path. This alternative is less portable than-path, so likeโฆ noted ๐ซถ.-writableโ matches files which are writable by the current user. This takes access control lists and other permissions artefacts into account, which the-permtest straight up ignores ๐. This test makes use of theaccess(2)system call, and so it can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implementaccess(2)in the client's kernel and so can't make use of the UID mapping information held on the server.-xtypec โ the same as-typeunless the file is a symbolic link. For symbolic links: if the-Hor-Poption was specified, true if the file is a link to a file of type c; if the-Loption has been given, true if c isl. In other words, for symbolic links,-xtypechecks the type of the file that-typedoes not check. And if a symbolic link is broken (because the thing it points to doesn't exist, or the link points to itself) then-xtypewill behave the same as-type.-contextpattern โ (SELinux only) the security context of the file matches the glob pattern.
๐ฌ ACTIONS ๐ฌ
-deleteโ deletes files or directories; true if the removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits).
โ ๏ธ Warning: don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. ๐ญ
The use of the -delete action on the command line automatically turns on the -depth option. And since -depth in turn makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, you might wanna test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it's usually best to remember to use -depth explicitly during those earlier test runs.
The -delete action will fail to remove a directory unless it's empty.
Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true.
-execcommand;โ executes 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 section for examples of the use of the-execoption. The specified command is run once for each matched file, and it's executed in the starting directory. There are unavoidable security problems surrounding use of the-execaction; you should use the-execdiroption instead, fr fr.-execcommand{}+โ this variant of the-execaction 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 invocations of the command will be much less than the number of matched files. The command line is built in much the same way thatxargsbuilds 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 invocation 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 pending commands may not be run at all. For this reason-exec my-command ... {} + -quitmay not result inmy-commandactually being run. This variant of-execalways returns true.-execdircommand;/-execdircommand{}+โ like-exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. Each selected file name except for the root directory/is prepended with./. As with-exec, the{}should be quoted if find is being invoked from a shell. This is a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the-execaction, the+form of-execdirwill 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 yourPATHenvironment variable does not reference.; otherwise, 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 inPATHwhich are empty or which are not absolute directory names. If any invocation 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 pending commands may not be run at all. The result of the action depends on whether the+or the;variant is being used;-execdir command {} +always returns true (though failed commands will affect find's eventual exit status), while-execdir command {} ;returns true only if command returns 0.-flsfile โ true; like-lsbut 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.-fprintfile โ 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/stdoutand/dev/stderrare handled 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 FILENAMES section for information about how unusual characters in filenames are handled.-fprint0file โ true; like-print0but 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.-fprintffile format โ true; like-printfbut 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.-lsโ true; list current file inls -dilsformat on standard output. The block counts are of 1 KiB blocks, unless the environment variablePOSIXLY_CORRECTis set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled.-okcommand;โ like-execbut 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-fromoption.
Okay bestie, so when you hit that prompt, your lil answer gets matched against a pair of regular expressions to figure out whether you said yes or no. ๐
Where does that regex come from? From the system, if the POSIXLY_CORRECT environment variable is set โ otherwise from find's own message translations. And if the system has no suitable definition? find just uses its own. Either way, how that regex itself gets interpreted is affected by the environment variables LC_CTYPE (for character classes) and LC_COLLATE (for character ranges and equivalence classes). No cap.
-okdircommand;โ literally-execdirbut it asks you first, same vibe as-ok. If you don't agree, it just returns false, no drama. If the command does run, its standard input gets redirected from/dev/null. Heads up: this action may not be specified together with the-files0-fromoption. ๐ซ-printโ True; prints the full file name on standard output, followed by a newline. But listen: if you're piping find's output into another program and there's even the faintest possibility that the files you're hunting might contain a newline, you should seriously consider using-print0instead of-print. (Check theUNUSUAL FILENAMESsection for how weird characters in filenames get handled.)-print0โ True; prints the full file name on standard output, followed by a null character instead of the newline that-printuses. This is the slay because it lets file names containing newlines or other types of white space get correctly interpreted by programs that process find's output. Fun fact: this option corresponds to the-0option ofxargs. ๐ซถ-printfformat โ True; prints format on standard output, interpreting\escapes and%directives. Field widths and precisions can be specified just like with theprintf(3)C function. โ ๏ธ Please note: lots of the fields print as%srather than%d, and that may mean flags don't work how you'd expect. It also means the-flag does work (it forces fields to be left-aligned). And unlike-print,-printfdoes not tack a newline onto 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 isNNN(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 Cctime(3)function.%Akโ File's last access time, in the format specified by k, which is either@or a directive for the Cstrftime(3)function. Here's an incomplete list of possible values for k โ please refer to the documentation ofstrftime(3)for the full list. Also ngl, some of the conversion specification characters might not be available on all systems, because implementations of thestrftime(3)library function differ. ๐ญ@โ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part (see below).
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 PMrโ time, 12-hour (hh:mm:ss [AP]M)Sโ Second (00.00 .. 61.00). There is a fractional part (see below).Tโ time, 24-hour (hh:mm:ss.xxxxxxxxxx); see below for details of the fractional part of the seconds field.+โ Date and time, separated by+, for example2004-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 theTZenvironment variable). The seconds field includes a fractional part (see below).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.
The length of the fractional part of seconds fields is of unspecified length and precision. Its length will in general vary between findutils releases and between systems. This means it is unwise to assume that field has any specific length. And the length of this field is not usually a guide to the precision of timestamps in the underlying file system. ๐
Date fields:
aโ locale's abbreviated weekday name (Sun..Sat)Aโ locale's full weekday name, variable length (Sunday..Saturday)bโ locale's abbreviated month name (Jan..Dec)Bโ locale's full month name, variable length (January..December)cโ locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as forctime(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 asbjโ 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 directive produces an empty string if the underlying operating system or filesystem doesn't support birth times. (๐ some of them just don't, bestie)%cโ File's last status change time, in the format returned by the Cctime(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;0means the file is a starting-point.%Dโ The device number on which the file exists (thest_devfield ofstruct stat), in decimal.%fโ Print the basename; the file's name with any leading directories removed (only the last element). For/, the result is/. See theEXAMPLESsection 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 (because it's in the current directory), the%hspecifier expands to.. For files which are themselves directories and contain a slash (including/),%hexpands to the empty string. See theEXAMPLESsection for an example.%Hโ Starting-point under which the file was found.%iโ File's inode number (in decimal).%kโ The amount of disk space used for this file in 1 KiB blocks. Since disk space is allocated in multiples of the filesystem block size, this is usually greater than%s/1024โ but again, it can also be smaller if the file is a sparse file.%lโ Object of symbolic link (empty string if the file is not a symbolic link). ๐%mโ File's permission bits (in octal). This option uses thetraditionalnumbers which most Unix implementations use โ but if your particular implementation uses an unusual ordering of octal permissions bits, you'll see a difference between the actual value of the file's mode and the output of%m. Normally you want a leading zero on this number, and to get that you should use the#flag (as in, for example,%#m).%Mโ File's permissions (in symbolic form, as forls). This directive is supported in findutils 4.2.5 (2004) and later. ๐%nโ Number of hard links to the 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โ the file's sparseness, bestie. It's computed as(BLOCKSIZE*st_blocks / st_size). The exact number you get for a normal file of a given length is system-dependent โ no cap. That said, sparse files usually come out less than1.0, and files that use indirect blocks can be greater than1.0. In general, how many blocks a file uses depends on the file system. TheBLOCKSIZEvalue used is also system-dependent, but it's usually512bytes. If the file size is zero, the value printed is undefined ๐. On systems that don't supportst_blocks, sparseness is just assumed to be1.0.%tโ the file's last modification time, in the format the Cctime(3)function returns.%Tkโ the file's last modification time, but in the format specified byk, which works exactly the same as for%A.%uโ the file's user name, or the numeric user ID if that user has no name.%Uโ the file's numeric user ID.%yโ the file's type (like inls -l), whereU=unknown type (which shouldn't happen ๐).%Yโ the file's type (like%y), plus it follows symbolic links:L=loop,N=nonexistent, and?for any other error when figuring out the type of a symbolic link's target.%Zโ (SELinux only) the file's security context.%{,%[,%(โ reserved for future use. โจ
A % character followed by any other character gets discarded, but that other character still gets printed. (don't rely on this, bestie โ more format characters might get introduced later ๐). And a % at the end of the format argument causes undefined behaviour, since there's 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're reading ๐. The %m and %d directives support the #, 0 and + flags, but the other directives do not โ even the ones that print numbers. Numeric directives that don't support these flags include G, U, b, D, k and n. The - format flag is supported, and it flips a field's alignment from right-justified (which is the default) to left-justified.
Peep the UNUSUAL FILENAMES section for the tea on how weird characters in filenames get handled.
-pruneโ true; and if the file is a directory, it does not descend into it. If-depthis given, then-prunehas no effect. And because-deleteimplies-depth, you can't usefully use-pruneand-deletetogether ๐ซ. For example, to skip the directorysrc/emacsand everything under it, while printing 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 happened). This is different from-prune, because-pruneonly applies to the contents of pruned directories, whereas-quitjust makesfindstop immediately. No child processes will be left running. Any command lines that were built by-exec ... +or-execdir ... +get invoked before the program exits. After-quitruns, no more files specified on the command line get processed. For example,find /tmp/foo /tmp/bar -print -quitwill print only/tmp/foo. One common use of-quitis to stop searching the file system once we've found what we wanted ๐ฏ. 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, babes:
( expr )โ forces precedence. Since parentheses are special to the shell, you'll normally need to quote them. A bunch of examples in this manual page use backslashes for this:\(...\)instead of(...).! exprโ true ifexpris false. This character will also usually need protecting from interpretation by the shell.-not exprโ same as! expr, but not POSIX compliant.expr1 expr2โ two expressions in a row get treated as joined with an implied-a;expr2is not evaluated ifexpr1is false.expr1 -a expr2โ same asexpr1 expr2.expr1 -and expr2โ same asexpr1 expr2, but not POSIX compliant.expr1 -o expr2โ OR;expr2is not evaluated ifexpr1is true.expr1 -or expr2โ same asexpr1 -o expr2, but not POSIX compliant.expr1 , expr2โ list; bothexpr1andexpr2are always evaluated. The value ofexpr1gets thrown away, and the value of the listexpr1 , expr2is the value ofexpr2. The comma operator is lowkey useful for searching for several different types of thing while only traversing the filesystem hierarchy once ๐. The-fprintfaction can be used to list the various matched items into several different output files.
Please note that-a, whether it's specified implicitly (like when two tests just appear with no explicit operator between them) or explicitly, has higher precedence than-o. This means thatfind afile bfile -name afile -o -name bfile -printwill never printafile. ๐ญ
๐ธ UNUSUAL FILENAMES ๐ธ
A lot of find's actions end up printing data that's under the control of other users. That includes file names, sizes, modification times and so forth. File names are a whole potential problem, because they can contain any character except \0 and /. Unusual characters in file names can do unexpected and often deeply undesirable things to your terminal (for example, changing the settings of your function keys on some terminals ๐). Unusual characters get 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 get printed using C-style escaping (for example \f, \"). Other unusual characters get printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) get printed as-is.
-printf, -fprintf
If the output is not going to a terminal, it gets 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 that are not under the control of files' owners, so they get printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values that are under the control of files' owners, but which can't be used to send arbitrary data to the terminal, so these also get printed as-is. The directives %f, %h, %l, %p and %P get quoted. This quoting is done the same way as for GNU ls. This is not the same quoting mechanism used for -ls and -fls. If you're able to decide what format to use for find's output, it's normally better to use \0 as a terminator than to use newline, since 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 gets handled the same way as for -printf and -fprintf. If you're 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 โจ
ok so if you want to be as POSIX-pilled as humanly possible, bestie, you set the POSIXLY_CORRECT environment variable. that's the move. ๐
here's what the POSIX standard (IEEE Std 1003.1-2024 Edition, iconic) actually specifies:
-Hโ supported, no notes, she's here, she works. ๐-Lโ also supported. slay.-nameโ supported, BUT the POSIX conformance of this one depends on the POSIX conformance of your system'sfnmatch(3)library function. as offindutils-4.2.2(2004), shell metacharacters (like*,?or[], for example) match a leading., because IEEE PASC interpretation 126 literally requires it. this is a glow-up / change from previous versions of findutils, just so you know.-typeโ supported. POSIX specifiesb,c,d,l,p,fands. GNU find also supportsD, which represents a Door, wherever the OS actually provides those. AND on top of that, GNU find lets you specify multiple types at once in a comma-separated list. multitasking queen. ๐ฆ-okโ supported. how the response gets interpreted depends on theyesandnopatterns you selected by setting theLC_MESSAGESenvironment variable. whenPOSIXLY_CORRECTis set, those patterns come from the system's definition of a positive (yes) or negative (no) response โ check your system's documentation fornl_langinfo(3), specificallyYESEXPRandNOEXPR. whenPOSIXLY_CORRECTis not set, the patterns come from find's own message catalogue instead.-newerโ supported. if the file you specify is a symbolic link, it is always dereferenced. this is a change from previous behaviour, which used to take the relevant time from the symbolic link itself; peep the HISTORY section below for the lore.-permโ supported. unsetting thePOSIXLY_CORRECTenvironment variable no longer allows the legacy+modevariant of/modeto be accepted. that ship has sailed, babe.
Other primaries โ the primaries -atime, -ctime, -depth, -exec, -group, -links, -mount, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. every single one. ๐ซถ
the POSIX standard also specifies parentheses (, ), negation ! and the logical AND/OR operators -a and -o.
everything else โ all other options, predicates, expressions and so forth โ are extensions beyond the POSIX standard. but ngl, a lot of these extensions are not unique to GNU find, so don't feel too special about it.
the loop thing (it's giving safety feature) ๐
the POSIX standard requires that find detects loops, and here's the exact requirement, verbatim:
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, periodt. but here's the tea: the link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. this can mean that GNU find will sometimes optimize 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 message. although this behaviour may be somewhat confusing, it is unlikely 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 cycles 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 necessary.
the -d option is supported for compatibility with various BSD systems, but bestie, you should use the POSIX-compliant option -depth instead. i'm literally begging. ๐
and heads up: 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. they're doing their own thing, main character energy only.
๐ ERRORS ๐
so the -ok and -okdir actions check for user confirmation by writing a prompt to the standard error output. important: these prompts are not error messages. don't let anyone gaslight you about that. most error messages produced by find are self-explanatory. error messages sometimes include a filename, and when this happens, the filename is quoted in order to prevent any unusual characters in the filename making unwanted changes in the state of the terminal (shoutout to the UNUSUAL FILENAMES section). the error messages produced by find are intended to be largely self-explanatory, but we provide short explanations here of some messages anyway. this list is incomplete, so don't come for us.
invalid predicate -foo
this means that the find command line included something that started with a dash or other special character (in this case -foo). the find program tried to interpret this as a test, action or option, but didn't recognise it. if it was intended to be a test, check what was specified against the documentation. if, on the other hand, the string is the name of a file which has been expanded from a wildcard (for example because you have a * on the command line), consider using ./* or just . instead. classic shell-globbing jumpscare, fr fr.
unexpected extra predicate
this usually happens if you have an extra parenthesis on the command line. for example:
find . -print )
yeah. one parenthesis too many. it happens to the best of us. ๐ญ
sanity check of the fnmatch() library function failed
please submit a bug report. you may well be asked questions about your system, and if you compiled the findutils code yourself, you should keep your copy of the build tree around. the likely explanation is that your system has a buggy implementation of fnmatch which looks enough like the GNU version to fool configure, but which doesn't work properly. fake it till you make it but make it badly. ๐
cannot fork
this normally happens if you use the -exec action or something similar (-ok and so forth) but the system has run out of free process slots. this is either because the system is very busy and the system has reached its maximum process limit, or because you have a resource limit in place and you've reached it. check the system for runaway processes (with ps or pstree, if possible). some process slots are normally reserved for use by root. ๐
๐ธ 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. she's the boss of everyone. ๐LC_COLLATEโ the POSIX standard specifies that this variable affects the pattern matching to be used for the-nameoption. GNU find uses thefnmatch(3)library function, and so support forLC_COLLATEdepends on the system library. this variable also affects the interpretation of the response to-ok; while theLC_MESSAGESvariable selects the actual pattern used to interpret the response to-ok, the interpretation of any bracket expressions in the pattern will be affected byLC_COLLATE.LC_CTYPEโ this variable affects the treatment of character classes used in regular expressions and also with the-nametest, if the system'sfnmatch(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. theLC_CTYPEenvironment variable will also affect 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 thePOSIXLY_CORRECTenvironment variable is set, this also determines the interpretation of the response to the prompt made by the-okaction.NLSPATHโ determines the location of the internationalisation message catalogues.PATHโ affects the directories which are searched to find the executables invoked by-exec,-execdir,-okand-okdir.POSIXLY_CORRECTโ determines the block size used by-lsand-fls. ifPOSIXLY_CORRECTis 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 standard error are diagnostics 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 translations.
TZโ affects the time zone used for some of the time-related format directives of-printfand-fprintf. ๐ฆ
๐ธ EXAMPLES ๐ธ
Like bestie, this is the part where it all clicks. Real commands, real vibes, go wild. ๐
โจ 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
Heads up bestie: 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. Efficiency queen behavior, honestly. ๐
Also still true: there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Can't fix that one, it's just the nature of the game. ๐ญ
๐ 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 examined without recursing into directories (in the case one of the starting points is one). Lowkey genius, no cap. โจ
๐ 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. Protecting your punctuation from the shell is self-care fr fr. ๐ซถ
In many cases, one might prefer the -exec ... + or better the -execdir ... + 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. One pass, two actions, zero wasted effort โ that's the main character energy we're bringing. ๐
๐ธ 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 discarded. 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. Math but make it cute. โจ
๐ 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 returns 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 emphasises 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. Okay so that's a whole paragraph but it's literally the plot twist of the whole page, so read it twice bestie. ๐
- 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 directories:
repo/project1/CVS
repo/gnu/project2/.svn
repo/gnu/project3/.svn
repo/gnu/project3/src/.svn
repo/project4/.git
Output:
repo/project1
repo/gnu/project2
repo/gnu/project3
repo/project4
In this example, -prune prevents unnecessary descent into directories that have already been discovered (here we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Ate. ๐ฅ
๐ The -xdev and -mount options ๐
Normally, find will search inside directories which happen to be mount points. In this example, tree/bound1 is a mount point:
$ find tree -printf 'device: %D path: %p\n'
device: 40 path: tree
device: 64770 path: tree/bound1
device: 64770 path: tree/bound1/on-another-fs
The -xdev option causes find to visit the mount point, but not the items within that directory:
$ find tree -xdev -printf 'device: %D path: %p\n'
device: 40 path: tree
device: 64770 path: tree/bound1
If we specify -mount we will not visit the mount point at all:
$ find tree -mount -printf 'device: %D path: %p\n'
device: 40 path: tree
See the difference? One still says hi to the mount point, the other straight up ghosts it. ๐
โญ Other useful examples โญ
- Search for several file types.
$ find /tmp -type f,d,l
Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), 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 immediately when we find the first one.
$ find / -name needle -print -quit
- Demonstrate the interpretation of the
%fand%hformat directives of the-printfaction 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 description, but if the return value is non-zero, you should not rely on the correctness of the results of find. Not a vibe. ๐ญ
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 ๐ฆ
A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmer's Manual, 1971โ1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. Deep lore, honestly iconic. ๐
GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. Shoutout to the whole squad, they understood the assignment. ๐
๐ CAVEATS ๐
okay bestie, real talk: so many of GNU find's features justโฆ don't exist on other systems. ๐ญ If you wanna know how this version of GNU find lines up with older GNU finds and with other people's finds, go read COMPATIBILITY. And if something seems weird and you're about to call it a bug โ check NON-BUGS first, because some of those "bugs" are literally just how it's supposed to work. ๐
๐ธ Future Directions for File Name Printing ๐ธ
So the -ls action quotes non-printable characters in file names using C-like backslash escapes. That might change someday โ like, if the treatment of unprintable characters ever gets harmonised across -ls, -fls, -print, -fprint, -printf and -fprintf. โจ
And heads up: Issue 8 of the POSIX standard says that in the future, the requirements for handling newlines in printed file names may change:
If this utility is directed to display a pathname that contains any bytes that have the encoded value of a <newline> character when <newline> is a terminator or separator in the output format being used, implementations are encouraged to treat this as an error. A future version of this standard may require implementations to treat this as an error.
The way to dodge future problems around this? use -print0 whenever file names might contain newline characters. periodt. ๐
โจ COMPATIBILITY โจ
๐ฆ Feature Additions
every single glow-up, in order of when it dropped ๐
-files0-fromโ added in4.9.0(2022) โญ-newerXYโ added in4.3.3(2007), also occurs in BSD ๐-Dโ added in4.3.1(2006)-Oโ added in4.3.1(2006)-readableโ added in4.3.0(2005)-writableโ added in4.3.0(2005)-executableโ added in4.3.0(2005)-regextypeโ added in4.2.24(2004)-exec ... +โ added in4.2.12(2005), also occurs in POSIX ๐ซถ-execdirโ added in4.2.12(2005), also occurs in BSD-okdirโ added in4.2.12(2005)-samefileโ added in4.2.11(2004)-Hโ added in4.2.5(2004), also occurs in POSIX-Lโ added in4.2.5(2004), also occurs in POSIX-Pโ added in4.2.5(2004), also occurs in BSD-deleteโ added in4.2.3(2004)-quitโ added in4.2.3(2004)-dโ added in4.2.3(2004), also occurs in BSD-wholenameโ added in4.2.0(2003)-iwholenameโ added in4.2.0(2003)-ignore_readdir_raceโ added in4.2.0(2003)-flsโ added in4.0(1994)-ilnameโ added in3.8(1993)-inameโ added in3.8(1993), also occurs in POSIX (from Issue 8, IEEE Std 1003.1-2024) ๐-ipathโ added in3.8(1993)-iregexโ added in3.8(1993)-print0โ added in2.0(1990), also occurs in POSIX (from Issue 8, IEEE Std 1003.1-2024) ๐
๐ Functional Changes
the lore of behaviour shifts, by version ๐ฐ๏ธ
4.11(2026) โ As required by newer POSIX (from Issue 8, IEEE Std 1003.1-2024), the test-mountis no longer a synonym for-xdev, and now skips the mount points themselves. ๐จ4.5.12(2013) โ The syntax-perm +MODEis removed, in favour of-perm /MODE. The+MODEsyntax had been deprecated sincefindutils-4.2.21(2005).4.3.11(2007) โ The-deleteaction setsfind's exit status to a nonzero value when it fails. However,findwill not exit immediately. Previously,find's exit status was unaffected by the failure of-delete.4.3.3(2007) โ Nanosecond-resolution timestamps; seconds fields are no longer integers.4.3.3(2007) โ-perm /000now matches all files instead of none.4.2.2(2004) โ Shell metacharacters (*,?or[]for example) used in filename patterns match a leading., because IEEE POSIX interpretation 126 requires this.
๐ซถ NON-BUGS ๐ซถ
๐ญ Operator precedence surprises
bestie. listen. The command find . -name afile -o -name bfile -print will never print afile โ because it's actually equivalent to find . -name afile -o \( -name bfile -a -print \). ๐ซ Remember: the precedence of -a is higher than that of -o, and when there's no operator specified between tests, -a is assumed. iykyk.
๐ "paths must precede expression" error message
this iconic little moment right here:
$ 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 pass the resulting 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 predicate 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 during the search for file name matching instead of file names expanded by the parent shell:
$ find . -name '*.c' -print
$ find . -name \*.c -print
๐ BUGS ๐
ngl, there are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. ๐ญ For example, the -exec action is inherently insecure, and -execdir should be used instead. ๐
Also: the environment variable LC_COLLATE has no effect on the -ok action. ๐
๐ REPORTING BUGS ๐
GNU findutils online help: https://www.gnu.org/software/findutils/#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โ2026 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 ๐
and that's a wrap on the whole page, bestie!! ๐โจ this page came from findutils, dated 2025-10-12, and it's the FIND(1) manual โ slay, go find some files, and remember: quote your wildcards. ๐
๐ซถ
๐ฆ where this page comes from
- arch rolling: findutils 4.11.0-1 ยท GPL-3.0-or-later
- ubuntu stonking: findutils 4.11.0-2 ยท GFDL-1.3-or-later-no-invariants OR GFDL-1.3-or-later-no-invariants
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms